Back End

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

PineappleCat · 5月12日 · 2021年 84次已读

会抛出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 */
          }
      }
  }

Click here to view the copyright notice of this site(点击此处查看本站版权声明)
0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!