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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With