Creating a Thread in Java With Examples

How to create a Thread?

Creating a thread is done by instantiating an object of type Thread. In Java, there are two ways to accomplish it. 

  • Implement the Runnable interface.
  • Extend the Thread class.

Let us discuss both the approaches followed by the decision of approaching either.

Implement the Runnable interface

The simplest way to create a thread is to create a class implementing the Runnable interface. It abstracts the unit of executable code. When we implement the Runnable interface, we need to implement the method run. 

Syntax:

 public void run( ){
//Code Constituting the thread
}

Inside this method, we need to write the code that serves the purpose of the new thread. This method can declare variables, use objects, call any method similar to the main thread.  It serves as an entry point for another, concurrent thread of execution inside our program. Upon completion of the execution of the run() method, the thread ends. 

After the class is created, we can instantiate the Thread type object using any of the constructors.

  • Thread()
  • Thread(String threadName)
  • Thread(Runnable threadOb)
  • Thread(Runnable threadOb,String threadName)

We will be using the last variant for our example. In this constructor, threadOb is an instance of a class that implemented the Runnable
interface. It specifies the starting point of the thread execution. We name the new thread using threadName. After the creation of the new thread, we need to call the method start(). This method is declared inside Thread and initiates the call to method run().  

Syntax:

void start( )

Example:

class MyThread implements Runnable{
    Thread tr;
    
    MyThread(){
        tr = new Thread(this,"My First Thread");
        System.out.println("Spawned Thread: "+tr);
    }
    
    public void run(){
        try{
            for(int i=0;i<3;i++){
                System.out.println("Spawned Thread: "+i);
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException obj){
            System.out.println("Spawned Thread Interrupted");
        }
        System.out.println("Exiting Spawned Thread");
    }
}

public class ClassMain{
    public static void main(String args[]){
        MyThread ob = new MyThread();
        ob.tr.start();
        
        try{
            for(int i=0;i<3;i++){
                System.out.println("Main Thread: "+i);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException obj){
            System.out.println("Main Thread Interrupted");
        }
        System.out.println("Exiting Main Thread");
    }
}

Output:

Spawned Thread: Thread[My First Thread,5,main]
Main Thread: 0
Spawned Thread: 0
Spawned Thread: 1
Main Thread: 1
Spawned Thread: 2
Exiting Spawned Thread
Main Thread: 2
Exiting Main Thread

We can see that inside MyThread's constructor, an object is instantiated. The first argument this, indicates that a new thread is required to call run().
Inside main(), start() is called, which initiates the thread execution i.e starting from run(). This causes the child thread’s the for loop to begin. Next, the main thread enters it's for loop.  Both the threads execute concurrently. We can see the method sleep() being called. This pauses the thread execution. Due to the difference in value(it is time in milliseconds), it causes the main method to be the last thread to finish.

Extend the Thread class

We can create a thread by creating a new class that extends Thread, and then to create an instance of that class. Here also, we need to override the run()
method, which is the entry point for the new thread. Similarly, call to start() initiates the execution of the new thread.  Let us look at the same example, but with a different approach to extending Thread.

class MyThread extends Thread{
    MyThread(){
        super("My First Thread");
        System.out.println("Spawned Thread: "+this);
    }
    
    public void run(){
        try{
            for(int i=0;i<3;i++){
                System.out.println("Spawned Thread: "+i);
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException obj){
            System.out.println("Spawned Thread Interrupted");
        }
        System.out.println("Exiting Spawned Thread");
    }
}

public class ClassMain{
    public static void main(String args[]){
        MyThread ob = new MyThread();
        ob.start();
        
        try{
            for(int i=0;i<3;i++){
                System.out.println("Main Thread: "+i);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException obj){
            System.out.println("Main Thread Interrupted");
        }
        System.out.println("Exiting Main Thread");
    }
}

Output:

Spawned Thread: Thread[My First Thread,5,main]
Spawned Thread: 0
Main Thread: 0
Spawned Thread: 1
Main Thread: 1
Spawned Thread: 2
Exiting Spawned Thread
Main Thread: 2
Exiting Main Thread

 The child thread is created by instantiating an object of NewThread, which is derived from Thread.

Which one to choose?

The Thread class defines several methods that can be overridden by a derived class. Thread classes should be extended only when they are being enhanced. Hence, if one has a requirement to override other methods as well prefer extending Thread class, else it is probably best simply to implement Runnable. Implementing Runnable allows extending some other important class which might be important to use. In final words, it completely depends on the purpose and requirement suiting best to the chosen approach.

This was an overview of how to create a Thread. We will discuss various methods of the Thread in the next lecture.