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.

Share:
12,767
Matt
Author by

Matt

SOreadytohelp

Updated on June 16, 2022

Comments

  • Matt
    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
    Matt about 13 years
    Oops.. 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
    dty about 13 years
    Where 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 extending Thread then the executor framework gives you the ability to re-submit a job, or have it run periodically, etc.
  • Matt
    Matt about 13 years
    download.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
    matt b about 13 years
    The javadoc means "It is never legal to call start() twice"
  • dty
    dty about 13 years
    Ah yeah. Then as @GregInYEG said. It's a bit like the isConnected() method on Socket - it just tells you that the socket has, at some point, been connected. Utterly useless!
  • TurtleToes
    TurtleToes about 13 years
    Don'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
    C. K. Young about 13 years
    Using wait and notify 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 as ThreadPoolExecutor) to do the thread parking for you.