016、—个线程两次调用start。方法会出现什么情况?

22

会抛出IllegalThreadStateException()

public class Main{
  public static void main(String[] args){
    Thread t1 = new Thread(()->{System.out.println("this is a thread");});
    t1.start();
    t1.start()
  }
}

之所以会抛出异常,是因为在start()函数里,会先检查线程的状态。如果线程的状态不为0,那么就抛IllegalThreadStateException。线程状态的初始值为0,当线程在第一次执行start()函数的时候,会将线程的状态进行改变。那么当线程第二次调用start()函数的候,会发现此时线程状态已经不为0了,自然就抛出异常。

Thread类的start()函数:

public synchronized void start() {
       /**
        * This method is not invoked for the main method thread or "system"
        * group threads created/set up by the VM. Any new functionality added
        * to this method in the future may have to also be added to the VM.
        *
        * A zero status value corresponds to state "NEW".
        */
       if (threadStatus != 0)
           throw new IllegalThreadStateException();

       /* Notify the group that this thread is about to be started
        * so that it can be added to the group's list of threads
        * and the group's unstarted count can be decremented. */
       group.add(this);

       boolean started = false;
       try {
           start0();
           started = true;
      } finally {
           try {
               if (!started) {
                   group.threadStartFailed(this);
              }
          } catch (Throwable ignore) {
               /* do nothing. If start0 threw a Throwable then
                 it will be passed up the call stack */
          }
      }
  }