Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we call the start method twice on a same instance of the Thread object?

Tags:

I was reading about threads and found that we can't call the start method twice on the same thread instance. But I didn't understand the exact reason for the same. So why can't we call it twice or even more times?

like image 562
GuruKulki Avatar asked Apr 18 '10 18:04

GuruKulki


2 Answers

In my opinion the Thread object is your "handle" for the actual running context. If you allow creating many concurrent executions associated with the same java.lang.Thread, what would you expect getStackTrace() and getState() methods to return?

I suppose that Thread class could have been designed to allow spawning multiple running contexts, but its API would be less simple and clean.

like image 166
Eyal Schneider Avatar answered Oct 07 '22 05:10

Eyal Schneider


You want 1 instance for 1 thread, as that thread has internal state it will manage.

Consider threads as a kind of resource. It usually does not make sense to have 1 instance refer to several resources - (just as you can't have a java File object refer to more than 1 file).

It would also get you in all sorts of trouble if you started a thread twice, and you either inherited from Thread and made some instance variables that now more than 1 thread accesses, - same thing if you create the thread from a Runnable. Atleast the API doesn't make it a no-brainer to do that screw-up.

Take a look at the states a thread can be in , here http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.State.html

Basically, the only time you can start a thread is when it is in the NEW state. And none of the other states can make it transition back to NEW

like image 32
leeeroy Avatar answered Oct 07 '22 05:10

leeeroy