views:

97

answers:

4

When a Thread is finished, you cannot run it once more, using start() method: it throws an Exception. Could anyone explain, why? What stands behind such an architectural decision?

+2  A: 

Ultimately, the thread lives, and then it dies. After all, the Thread object is just a proxy for the real OS thread underneath. If you want another like it, make a new instance. Don't try to resurrect the undead!

Donal Fellows
+6  A: 

Because the way to have code executed in a separate thread is not to create a thread, which is linked to system view of what is a thread (there are endless details on distinction between green and system threads), but to create a Runnable, and have it executed by a Thread.

For optimal code (since creation of threads is time-consuming), I would even recommand you not to directly have your Runnable executed by a thread, but rather by an ExecutorService, which will allow you to use a thread pool without bothering about all those details.

Riduidel
Yes! ExecutorService is the shit, it can also handle a BlockingQueue.
Lars Andren
A: 

What would be even worse in an architectural sense is if the thread never finished, and you had to arbitrarily kill it to stop it from executing.

Place a loop inside your run() method if you want it to execute a routine more than once. You can use a callback method to send data/signals back to the calling thread, and react on them when they occur.

seanhodges
I don't want to know, how to work around this, I just want to know, why.
folone
+4  A: 

When a Thread is finished, you cannot run it once more, using start() method:

Correction: you can call Thread.start() only once per instance, any subsequent call will throw an exception, no matter whether the thread is still running or not.

Allowing a "restart" after it has finished running (it's clearly an error while the thread is still running) would require extra logic, and would prevent the runtime from releasing resources like the thread stack (which is a significant amount of memory) until the instance is garbage collected; the way it is now, those can be released as soon as the thread finishes.

Michael Borgwardt