Can we start a Thread twice in Java

Can we start a thread twice in Java? The answer is no, once a thread is started, it can never be started again. Doing so will throw an IllegalThreadStateException.

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Let's understand it by the example given below:
public class Test extends Thread { public void run() { System.out.println("running..."); } public static void main(String args[]) { Test t1=new Test(); t1.start(); t1.start(); } }


Output:
running Exception in thread "main" java.lang.IllegalThreadStateException
Lets have a look at the below code:
public class Test implements Runnable { @Override public void run(){ Thread t = Thread.currentThread(); System.out.println(t.getName()+" is executing."); } public static void main(String args[]){ Thread th1 = new Thread(new Test(), "th1"); th1.start(); th1.start(); } }


Output:
Exception in thread "main" th1 is executing. java.lang.IllegalThreadStateException

As you observe the first call to start() resulted in execution of run() method, however the exception got thrown when we tried to call the start() second time.




Instagram