Create a Thread


To create a thread by instantiating an object of Thread.

 

There are two different ways to create a thread:

 

  • By extending Thread class
  • By implementing the Runnable interface.

By implementing the Runnable interface

The simplest way to create a thread is to create a class which implements the Runnable interface.


Step 1

The Runnable interface provides the run() method which you need to implement.

 

You should implement your complete business logic inside this run() method.

 

 public void run()

Step 2

When you create a class that implements Runnable then You should instantiate thread object within that class.

 

Thread(Runnable threadObj, String threadName); 

Hence, threadObj is an instance of a class that implements the Runnable interface and threadName provided to the new thread.


 void start();

Example

By implementing the Runnable interface

 public class ThreadRunnable implements Runnable{  
    public void run(){  
        System.out.println("Running...");  
    }  
    public static void main(String args[]){  
        ThreadRunnable tr=new ThreadRunnable();  
        Thread t =new Thread(tr); 
        t.start(); 
    }  
}  

By extending Thread class

If you want to create a thread, you should create a new class that extends Thread class.

 

You will need to override run( ) method available in Thread class, which is the entry point for the thread.

 

You should implement your complete business logic inside this run() method.

 

It should call the start( ) method to start execution of the new thread.


Example

By extending Thread class

 public class Threadextends extends Thread{  
    public void run(){  
        System.out.println("Running...");  
    }  
    public static void main(String args[]){  
        Threadextends tr=new Threadextends();  
        tr.start(); 
    }  
} 



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.