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
. Lets have a look at the below code:
public class ThreadTwiceExample 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 ThreadTwiceExample(), "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.
juvin says
hello,
you are doing a very good job in clarifying the java basics for the newbies …
please keep doing it more and more on more topics.. :) (greedy me :p )
i have a doubt.
the same thread cannot be started multiple times. what if i instantiate the class again and then start it again?
ti = new ThreadclassName();
ti.start;
t2= new ThreadclassName();
t2.start();
is this possible?
Neeraj says
Hi Juvin,
It is possible if we instantiate same class again and invoke run method by start, the program will compile successful.Now we are not running same thread.