April 3, 2024

How to Create And Start Thread in Java

In order to create a thread in Java you need to get an instance of java.lang.Thread class. You can do it in two ways.

  1. By implementing Runnable interface.
  2. By Extending Thread class.

Whichever of these two ways is chosen by you to create a thread in Java you need to override run() method and provide the code that will run in that thread. Thread’s run() method will be executed once you call start() method on the created thread.

Creating and starting thread in Java involves the following steps.

  1. Get an instance of the Thread class.
  2. Call start method on the created thread object- thread.start();
  3. Once the thread is started run method will be executed.

Creating thread by implementing Runnable interface

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

Runnable interface is a functional interface in Java with a single method run() which has to be implemented. That's how Runnable interface is defined in java.lang package.

@FunctionalInterface
public interface Runnable {
  public abstract void run();
}
Example code using Runnable
public class TestThread implements Runnable {
  @Override
  public void run() {
    System.out.println("Executing run method");
  }
}

At this stage you have a class of type Runnable (not yet of type Thread). Thread class has constructors where you can pass Runnable as a parameter, using one of those constructors you can get a thread instance.

Two of those constructors which are normally used to create a thread are as follows-

  • Thread(Runnable target)
  • Thread(Runnable target, String name)

You need to pass the Runnable instance to one of these constructors to create a thread. Following code shows how you can do it.

public class ThreadDemo {
  public static void main(String[] args) {
    // Passing an instance of type runnable 
    Thread thread = new Thread(new TestThread());
    thread.start();
  }
}

Running this code will instantiate a thread and start it. Ultimately the run() method will be executed by the thread.

Output
Executing run method

Creating thread by extending Thread class

Another way to create thread in Java is to subclass the Thread class and override the run method. Then you can create an instance of that class and call start() method.

public class TestThread extends Thread {
  @Override
  public void run() {
    System.out.println("Executing run method");
  }
  public static void main(String[] args) {
    TestThread thread = new TestThread();
    thread.start();
  }
}
Output
Executing run method

Which of these approach to choose

Since there are two ways to create thread in Java so the question arises which of these two approach should be used. The preferred way is to implement Runnable interface.

When you implement Runnable interface you still have a choice to extend another class as you are not extending Thread class. Note that in Java you can extend only one class.

Thread class has many other methods except run() method but mostly you will just override run() method and provide the code that has to be executed by the Thread. Same thing can be done by implementing Runnable interface. If you are not modifying or enhancing any other method of the Thread class then why extend it.

Using anonymous class to implement run() method

When creating thread in Java by extending Thread class or implementing Runnable interface, you can also use anonymous class to implement run method.

When extending Thread class

We can have an anonymous inner class that extends a class without actually extending that class. You can create an anonymous inner class and provide run method implementation there.

public class TestThread {
  public static void main(String[] args) {
    //  anonymous inner class
    Thread thread = new Thread(){
      @Override
      public void run() {
        System.out.println("Executing run method");
      }
    };
    thread.start();
  }
}
When implementing Runnable interface
public class TestThread {
  public static void main(String[] args) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("Executing run method");
      }
    }).start();
  }
}
Implementing Runnable as a lambda expression

Since Runnable is a functional interface it can also be implemented as a lambda expression Java 8 onward.

public class TestThread {
  public static void main(String[] args) {
    Runnable r = () -> {System.out.println("Executing run method");};
    // passing runnable instance
    new Thread(r).start();
  }
}

That's all for the topic How to Create And Start Thread in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment