October 6, 2022

Can we Start a Thread Twice in Java

Can we start a thread twice in Java is a frequently asked Java interview question. The short answer is no and this post tries to explain why it is not possible to call start() method twice on the same thread in Java.

Thread is terminated after run() method

As explained in the post Life Cycle of a Thread (Thread States) in Java once the thread finishes executing its run() method, it goes to terminated state (i.e. thread is dead). Since the thread object is already dead so calling start() method on the thread is not permitted and an exception is thrown.

As per the Java docs- It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws: IllegalThreadStateException - if the thread was already started.

Reference: https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Thread.html#start()

Thus a Thread can only be started once, trying to start the same thread again in Java will throw IllegalThreadStateException.

Java example code

public class ThreadTwiceDemo implements Runnable{
  public static void main(String[] args) {
    Thread t = new Thread(new ThreadTwiceDemo());
    t.start();
    // Calling start method again on same thread object
    t.start();
  }

  @Override
  public void run() {
    System.out.println("In run method");    
  }
}
Output
In run method
Exception in thread "main" 
java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Unknown Source)
	at com.knpcode.ThreadTwiceDemo.main(ThreadTwiceDemo.java:9)

As you can see in the output IllegalThreadStateException is thrown when we are trying to start a thread twice.

That's all for the topic Can we Start a Thread Twice 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