Why does an IllegalThreadStateException occur when Thread.start is called again

后端 未结 7 1755
攒了一身酷
攒了一身酷 2020-12-01 16:15
public class SieveGenerator{

static int N = 50;
public static void main(String args[]){

    int cores = Runtime.getRuntime().availableProcessors();

    int f[] =          


        
7条回答
  •  囚心锁ツ
    2020-12-01 16:41

    Why does an IllegalThreadStateException occur when Thread.start is called again

    Because JDK/JVM implementers coded Thread.start() method that way. Its a reasonable functional expectation to be able to restart a thread after a thread has completed its execution and that is what being suggested in chrisbunney's answer ( and I have put in a comment in that answer ) but if you look at Thread.start() implementation , the very first line is ,

    if (threadStatus != 0)
                throw new IllegalThreadStateException();
    

    where threadStatus == 0 means NEW state so my guess is that implementation doesn't resets this state to zero after execution has completed & thread is left in TERMINATED state ( non - zero state ). So when you create a new Thread instance on same Runnable , you basically reset this state to zero.

    Also, I noticed the usage of word - may & never in same paragraph as different behavior is being pointed out by Phan Van Linh on some OSes,

    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

    I guess what they are trying to say in above Javadoc that even if you don't get IllegalThreadStateException on certain OS, its not legal in Java/Thread class way & you might get unexpected behavior.

    The famous thread state diagrams depict the same scenario - no going back from dead state to new.

提交回复
热议问题