$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,16,Arrays,3,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,74,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,52,Java 8 Difference,2,java 8 Stream Examples,1,Java 9,1,Java Conversions,12,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,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,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,13,String,57,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,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://1.bp.blogspot.com/-0vU3Ao2LDoc/XiCSLTZnRcI/AAAAAAAACM4/9CtMqu3FTLoUL8ogdMwvmoYzKu1PjvBZQCLcBGAsYHQ/s640/Creating%2BThread%2BIn%2BJava%2B-%2BMultithreading%2BTutorial.png
https://1.bp.blogspot.com/-0vU3Ao2LDoc/XiCSLTZnRcI/AAAAAAAACM4/9CtMqu3FTLoUL8ogdMwvmoYzKu1PjvBZQCLcBGAsYHQ/s72-c/Creating%2BThread%2BIn%2BJava%2B-%2BMultithreading%2BTutorial.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