If I use start() on a Thread object and the run() method returns, is it possible to call start() again?
eg,
MyThread myThread = new MyThread();
myThread.start();
// run method executes and returns in 2 seconds
// sleep for 5 seconds to make sure the thread has died
myThread.start();
I'm just wondering because my code is throwing IllegalThreadStateExceptions, so want to know if it's because you can't do the above.
In dead state, the thread object is garbage collected. It is the end of the life cycle of thread. Once a thread is removed, it cannot be restarted again (as the thread object does not exist).
If you look at the Thread Life Cycle Image, there is no way you can go back to new position once your thread has terminated. So there is no way to bring back the dead thread to runnable state ,instead you should create a new Thread instance. Show activity on this post.
A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Once a thread enters dead state it cannot be restarted.
How can dead thread be restarted in Java? 1 New − A new thread begins its life cycle in the new state. ... 2 Runnable − After a newly born thread is started, the thread becomes runnable. ... 3 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. ... More items...
No, you can't. And the Javadoc for the Thread.start()
method tells you that!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With