Can I start a thread again after it has died?
12,767
Solution 1
No, you can't. And the Javadoc for the Thread.start()
method tells you that!
Solution 2
From a comment:
Is there anything else I could do to re-start a thread?
You could use ThreadPoolExecutor
, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
So, you don't restart a thread, but you would redo/resume a task.
Comments
-
Matt almost 2 years
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.
-
Matt about 13 yearsOops.. so does "started" mean "has been started at some point", rather than "not dead"? Is there anything else I could do to re-start a thread?
-
dty about 13 yearsWhere does 'started' appear? The documentation I'm looking at says "It is never legal to start a thread more than once". If you have written a
Runnable
instead of extendingThread
then the executor framework gives you the ability to re-submit a job, or have it run periodically, etc. -
Matt about 13 yearsdownload.oracle.com/javase/1.4.2/docs/api/java/lang/… "Throws: IllegalThreadStateException - if the thread was already started." But thanks, at least I know now.
-
matt b about 13 yearsThe javadoc means "It is never legal to call
start()
twice" -
dty about 13 yearsAh yeah. Then as @GregInYEG said. It's a bit like the
isConnected()
method onSocket
- it just tells you that the socket has, at some point, been connected. Utterly useless! -
TurtleToes about 13 yearsDon't know why you would downvote it... it works in C++... starting a new thread every time you need the same thread is a waste... if you need the same thread to retain itself, it's better to simply pause and resume it.
-
C. K. Young about 13 yearsUsing
wait
andnotify
is totally the wrong way to go about parking a thread for use in executing multiple tasks. The right way, BTW, is to use an executor (such asThreadPoolExecutor
) to do the thread parking for you.