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

后端 未结 5 1452
孤街浪徒
孤街浪徒 2020-12-03 03:16

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

5条回答
  •  悲哀的现实
    2020-12-03 03:47

    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

提交回复
热议问题