Terminated Thread Revival

moejoe picture moejoe · Mar 23, 2011 · Viewed 8.7k times · Source

I am storing a bunch of threads objects in an arraylist. I want to be able to start these threads at random. Same thread can be started more than once. Before I start a thread object, I check on whether the thread is alive, and if they have either of NEW or TERMINATED status. This restriction because, I don't want to disturb the 'busy' threads. Now, for NEW threads, this works fine. But for TERMINATED thread, I get an exception.

When a thread ends, shouldn't it go back to being 'new'? Or are threads 'disposable' - like use once and done?

Answer

Esko Luontola picture Esko Luontola · Mar 23, 2011

As it says in the documentation for Thread.start(), "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

It is better for you to keep hold of Runnable instances and implement your own logic for keeping track of when the execution of each one of them finishes. Using an Executor is probably the simplest way to run the Runnables.