$show=/label

Creating Thread In Java - Multithreading Tutorial

SHARE:

A quick guide to create a thread in java using different ways. Thread can be created using Thread class and Runnable interface.

1. Introduction


In this tutorial, We'll be learning how to create a thread in java. Before going to thread creation we should understand first the basic things about processors in our devices such as laptops and mobile smartphones.
Nowadays, we can use different applications at the same time. This can be working with Microsoft word document while listening to music or playing a game online. we can do all these things because we have an operating system that supports all of these.

Apart from different applications, we can do different works in one application. For instance, eclipse we can do write program and parallel we can run a search or building the application. Because our modern programming languages support to allow running multiple threads that run different tasks.

Coming to java, A Thread can be created in two ways as below.

A) Using Thread class
B) Using Runnable interface but we need to pass the object of this class to Thread class constructor.

Thread is a from java.lang package and Runnable is from java.util package.

Creating Thread In Java - Multithreading Tutorial




Before going to Thread creation, JVM will create a default thread when you start executing the Main program that has main() method. Just write a demo main program and see the name of the current execution thread using Thread.currentThread().getName() method.

package com.java.w3schools.blog.java.program.to.threads;

public class MainThread {

 public static void main(String[] args) {

  System.out.println("is this main thread?");
  String threadName = Thread.currentThread().getName();
  System.out.println("Let us see what is the current thread name: " + threadName);

 }

}

Output:

is this main thread?
Let us see what is the current thread name: main

Note: JVM creates a new Thread that executes main() method and this is the first thread in concurrent and non-concurrent applications.

2) Extending Thread Class


This is very simple to create new thread objects. To make a class get threading power that class just needs to extend Thread class. Next is to create the object and call start() method.

Take a look at the below class that extends Thread class and overridden run() method implementation.


class PrintNumbersThread extends Thread {

 @Override
 public void run() {

  IntStream.range(1, 11).forEach(n -> System.out.println(Thread.currentThread().getName() + " - " + n));

 }

}

The above class prints numbers from 1 to 10 using a thread and IntStream.range() method. As well, the run() method will be printing the current execution thread name and a number.

Now, We will create two threads and all start() method to start two new threads.

package com.java.w3schools.blog.java.program.to.threads;

import java.util.stream.IntStream;

public class ThreadExtendsClass {

 public static void main(String[] args) {

  PrintNumbersThread numbers1 = new PrintNumbersThread();
  numbers1.setName("PrintNumbers Thread 1");
  numbers1.start();

  PrintNumbersThread numbers2 = new PrintNumbersThread();
  numbers2.setName("PrintNumbers Thread 2");
  numbers2.start();

 }
}

Let us see the output. Every time you run the program, you will see the different outcomes. Because we or JVM do not know who will get the chance to execute first.

PrintNumbers Thread 2 - 1
PrintNumbers Thread 1 - 1
PrintNumbers Thread 2 - 2
PrintNumbers Thread 1 - 2
PrintNumbers Thread 2 - 3
PrintNumbers Thread 1 - 3
PrintNumbers Thread 2 - 4
PrintNumbers Thread 1 - 4
PrintNumbers Thread 1 - 5
PrintNumbers Thread 2 - 5
PrintNumbers Thread 1 - 6
PrintNumbers Thread 2 - 6
PrintNumbers Thread 1 - 7
PrintNumbers Thread 2 - 7
PrintNumbers Thread 1 - 8
PrintNumbers Thread 2 - 8
PrintNumbers Thread 1 - 9
PrintNumbers Thread 2 - 9
PrintNumbers Thread 1 - 10
PrintNumbers Thread 2 - 10

Note: Here we have create two objects of PrintNumbersThread to create two new threads. See in the next section to understand more about this.

3) Implementing Runnable Interface


We are now seeing the second way to create threads using the Runnable interface. We have created a class PrintNumberRunnable that implements Runnable. Runnable interface has run() method and this has to be implemented by implementation class.


package com.java.w3schools.blog.java.program.to.threads;

import java.util.stream.IntStream;

/**
 * 
 * Runnable - Thread creation examples.
 * 
 * @author JavaProgramTo.com
 *
 */

public class ThreadImplementsRunnable {

 public static void main(String[] args) {

  PrintNumberRunnable numberRunnableThread = new PrintNumberRunnable();

  Thread t1 = new Thread(numberRunnableThread);
  t1.setName("Runnable Thread 1");
  t1.start();

  Thread t2 = new Thread(numberRunnableThread);
  t2.setName("Runnable Thread 2");
  t2.start();

 }
}

Implementing Runnable Interface Example:

class PrintNumberRunnable implements Runnable {

 @Override
 public void run() {

  IntStream.range(1, 11).forEach(n -> System.out.println(Thread.currentThread().getName() + " - " + n));

 }

}

This program compiles and runs fine and produces a random output as see in thread creation using Thread class. But, here created only one object for PrintNumberRunnable class and passed the same object to two threads. This is the flexibility that comes with the Runnable Interface.

4) Thread Class VS Runnable Interface


If you see in both examples, We need to create the Thread class object but 100% the second approach implementing the Runnable interface approach is preferred by all developers.

Take a look at the following advantages over the Thread class.

A) This is straight forward. Runnable is an interface that means when a class implementing an interface that class can extend a class. Here using the Runnable interface, can allow implementing the Runnable interface and extend another class. But if we use Thread class to create a thread then we can extend only Thread class.
B) Runnable implementation class objects can be used as another powerful concurrency feature Executors. This gives you more flexibility to change your concurrent applications.
C) One Runnable object can be used with different threads.

Note: Once a Thread object is created then you must invoke the start() method to create a new thread execution that calls run() method of Thread. But, If you call directly run() method then no new Thread will be created. This is exactly equal to the normal method invocation. Freshers who are not having sufficient knowledge on threads will call run() method directly.


5. Conclusion


In this article, We've seen the methodologies for creating a thread in java. Example program on Thread class and Runnable interface.

Finally, Seen the differences between Thread creation using Thread class and Runnable Interface.

Next, read the article on how to stop a thread, Thread class stop() method is deprecated but this concept is tricky to understand.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Creating Thread In Java - Multithreading Tutorial
Creating Thread In Java - Multithreading Tutorial
A quick guide to create a thread in java using different ways. Thread can be created using Thread class and Runnable interface.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjX4FbNo2G_5b7Nci4_O319TO1VRl0Ijs1LfK1_GhNayNJQ-YcmDLBUfCKWHbRJLcgxsL5j-MoE7QIa4YZE4btIRf7eWY3fp49kW2t7qFGRG4CXz5hbY4k-zLKIs_0rdaqB9Xb00Gnx6Ws/s640/Creating+Thread+In+Java+-+Multithreading+Tutorial.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjX4FbNo2G_5b7Nci4_O319TO1VRl0Ijs1LfK1_GhNayNJQ-YcmDLBUfCKWHbRJLcgxsL5j-MoE7QIa4YZE4btIRf7eWY3fp49kW2t7qFGRG4CXz5hbY4k-zLKIs_0rdaqB9Xb00Gnx6Ws/s72-c/Creating+Thread+In+Java+-+Multithreading+Tutorial.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/01/java-thread-create.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/01/java-thread-create.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content