Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I start a thread again after it has died?

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.

like image 369
Matt Avatar asked Mar 22 '11 22:03

Matt


People also ask

What happens when a thread is dead?

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).

How to bring a dead thread back to its state?

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.

What is the difference between runnable thread and dead thread?

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 to restart a dead thread in Java?

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...


1 Answers

No, you can't. And the Javadoc for the Thread.start() method tells you that!

like image 187
dty Avatar answered Oct 06 '22 07:10

dty