Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread runs only once

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?

like image 962
George Avatar asked Apr 22 '10 08:04

George


1 Answers

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.

like image 70
Riduidel Avatar answered Oct 10 '22 19:10

Riduidel