Thursday, March 28, 2019

Creating a Thread in Java

To create a thread in Java you need to instantiate an object of type Thread. Java provides two ways to create a thread-

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

Here we'll look at both the ways of creating a thread in Java.


Implementing Runnable interface

One of the ways to create a thread in Java is to implement the Runnable interface.

@FunctionalInterface
Interface Runnable {
    public abstract void run();
}

To implement Runnable, a class has to implement only the run() method. Inside run() method we write the code for the new thread.

When using Runnable you have to explicitly create a Thread class object by passing the Runnable as parameter so that run() method of the thread can be executed. Java Thread class defines several constructors, some of the commonly used are.

Thread()
Thread(String name)
Thread(Runnable threadObj)
Thread(Runnable threadObj, String name)

You can use any of the last two in case of Runnable to create a thread in Java.

After the new thread is created, it will not start running until you call the start() method, which is declared within Thread class. As soon as start() method is called upon a thread object following actions happen-

  • The thread's state changes from New state to the Runnable state.
  • Thread's target run() method will execute (depends upon when thread gets the CPU cycle).

Java Thread creation Example using Runnable

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println("Entered run method " +Thread.currentThread().getName());
        for(int i = 0; i < 5; i++){
            System.out.println("My Thread" + i);
        }
        System.out.println("Finished with MyThread");      
    } 
}

public class ThreadDemo {
    public static void main(String[] args) {   
      // Passing runnable instance
      Thread thread = new Thread(new MyThread());
      // Calling start method
      thread.start();
    }
}

Output

Entered run method Thread-0
My Thread0
My Thread1
My Thread2
My Thread3
My Thread4
Finished with MyThread

Here we are using the constructor Thread(Runnable threadObj) while creating a thread object - Thread thread = new Thread(new MyThread());.

Calling start() method on the thread will execute the run method where it will print numbers along with the thread name.

Creating thread by extending Thread class

Another way to create a thread in Java is to create a class that extends Thread class and then create an instance of that class. The extending class has to override the run() method and also needs to call start() method to start execution of the new thread.

Thread creation Example by extending Thread class

class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("Entered run method " +Thread.currentThread().getName());
        for(int i = 0; i < 5; i++){
            System.out.println("My Thread" + i);
        }
        System.out.println("Finished with MyThread");  
    }
}

public class ThreadDemo {
    public static void main(String[] args) {   
      MyThread thread = new MyThread();
      thread.start();
    }
}

Here we are extending the thread class so we just need to create an instance of that class that will be a thread object. Then we are calling start() method on that thread object.

So these are the 2 ways provided in Java to create a new thread.

There are some other ways we can implement the run() method like, as an anonymous class and starting Java 8 using a lambda expression. Lets see how that can be done.

Creating Java thread as an anonymous class

class InnerThread{
    Thread t;
    // Constructor
    public InnerThread(String name) {
        // Anonymous class with run method implemented
        Thread t = new Thread(name){
            @Override
            public void run(){
                System.out.println("Entered run method " +Thread.currentThread().getName());
                for(int i = 0; i < 5; i++){
                    System.out.println(name + i);
                }
                System.out.println("Finished with Inner Thread");            
            }
        };
        // starting the thread, which will start execution of run method
        t.start();
    }
}

public class ThreadDemo {
    public static void main(String[] args) { 
     InnerThread thread = new InnerThread("MyThread");
    }
}

Here we are implementing the run method using an anonymous class. Note that Thread class is not explicitly extended here and the implementation of the run() method is provided when an instance of the thread is created.

Implementing Runnable as an anonymous class

If you want to do it using runnable interface run() method implementation it will only be a small change.

class InnerThread{
    Thread t;
    // Constructor
    public InnerThread(String name) {
        // Anonymous class with run method implemented
        // using Runnable interface
     Thread t = new Thread(new Runnable(){
            @Override
            public void run(){
                System.out.println("Entered run method " +Thread.currentThread().getName());
                for(int i = 0; i < 5; i++){
                    System.out.println(name + i);
                }
                System.out.println("Finished with Inner Thread");            
            }
      }, name);// Name of the thread, second param
        // starting the thread, which will start execution of run method
        t.start();
    }
}

Implementing Runnable as Java Lambda expression

Java 8 onward it is also possible to use lambda expression to provide implementation of the run method of the runnable interface. Runnable interface has a single abstract method run() thus it can be considered as a functional interface. Lambda expression can be used to provide implementation of that abstract method.

class LambdaThread{
    public LambdaThread(String name){
        // Lambda block - code inside the lambda block will
        // be the implementation of the run method. 
        Runnable r = () -> {
            System.out.println("Entered run method " +Thread.currentThread().getName());
            for(int i = 0; i < 5; i++){
                System.out.println("Lambda thread " + i);
            }
            System.out.println("Finished with Lambda Thread");
        };    
        //starting thread with the constructor of the thread class
        // that takes runnable instance and String as parameters
        new Thread(r, name).start();
    }
}

public class ThreadDemo {
    public static void main(String[] args) { 
     LambdaThread thread = new LambdaThread("LambdaThread");
    }
}

Here we have used the lambda expression to provide implementation of the run method of the runnable interface. Lambda block provides the implementation of the run() method of the runnable interface. It is possible because runnable interface is a functional interface and provided target type for the lambda expression.

So these are the ways you can create a thread in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Thread States in Java Multi-Threading
  2. Difference Between Thread and Process in Java
  3. Can we Start The Same Thread Twice in Java
  4. What if run() Method Called Directly Instead of start() Method
  5. Java Multi-Threading Interview Questions

You may also like-

  1. How to Loop Through a Map in Java
  2. How HashMap Internally Works in Java
  3. Count Total Number of Times Each Character Appears in a String - Java Program
  4. final Vs finally Vs finalize in Java
  5. Try-With-Resources in Java Exception Handling
  6. static Import in Java
  7. final in Java
  8. Serialization in Java