Thread in Java

By | May 4, 2020

In this tutorial, we will learn ways to create a Thread in Java. There are two ways to create the thread in Java first one is by extending Thread class and the second one is by implementing Runnable interface.

Creating a thread using Thread Class:

Thread class contain constructors and methods which helps us to create a thread. Check out these few steps to create a thread using Thread class.

  • First of all, inherit Thread class in your class.
  • Override the run() method in your class.
  • Use the start() method to start your thread.

Check out the following example. To understand it more wisely.

Example Program:

//Inherting Thread class in Example class
public class Example extends Thread{
      //Overiding run method 
      public void run(){
          for(int i=0;i<5;i++){
            System.out.println(i);
          }                       
      }
  
     public static void main(String args[]){
       Example obj=new Example();
       obj.start(); //using start() method to start thread
     }
}

Output:

0
1
2
3
4

Creating a thread using the Runnable interface:

We know multiple inheritance is not allowed in Java and we know to perform multi-threading we have to inherit Thread class in our class. But in some scenarios, if a class already inheriting another class we cannot inherit Thread class. So in this kind of situation, we can implement Runnable interface to create a thread in class.

Runnable interface contains only one method which is run() method.

Example Program:

//Implementing Runnable interface in Example class
public class Example implements Runnable{
      //Overiding run method 
      public void run(){
          for(int i=0;i<5;i++){
            System.out.println(i);
          }                       
      }
  
     public static void main(String args[]){
       Example obj=new Example();
       Thread thread=new Thread(obj); 
       thread.start();//using start() method to start thread
     }
}

Output:

0
1
2
3
4

It is important to note we know Runnable interface contains an only a single method which is run(). But we need to start() method to start a thread. So to get this start method we create an object of Thread class(check 12th line in the above example code) and we pass the object of our class in Thread class constructor. After that, we called the start method using thread class object.

Example Program:

public class Example {
     public static void main(String args[]){ 
       Thread thread=new Thread(new Runnable(){
         public void run(){
          for(int i=0;i<5;i++){
            System.out.println(i);
             }                       
           }
       }); 
       thread.start();//using start() method to start thread
     }
}

Output:

0
1
2
3
4