线程start之后发生了什么

// 注意这里是加了锁的,保证了线程安全
// 避免多个线程同时对一个线程调用start,从而导致非NEW状态的线程再次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)
    	// 如果线程不是处于NEW状态,则会报错。也就是只能处于NEW状态的线程才能调用start方法
        throw new IllegalThreadStateException();

    // 线程组需要维护自己的运行线程
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
            	// 如果start失败,线程组也需要维护。
            	// 逻辑是:1. 从数组中删除该线程(之前刚添加的);2. nUnstartedThreads++;
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

总结

  • 确保线程处于NEW状态
  • 添加到线程组的数组中
  • 尝试启动线程
  • 线程启动失败的时候需要线程组维护状态

线程的状态

public enum State {
        //尚未执行start方法
        NEW,
      
        // 已经在虚拟机中运行,但是可能等待其它资源,比如处理器
        RUNNABLE,

        // 等待monitor lock
        BLOCKED,
        
        // 等待其他线程的动作
        // 可能由以下方法导致
        // 1. Thread.join
        // 2. Object.wait
        // 3. LockSupport.park
        WAITING,
     
        // 处于有限等待状态,可能由以下方法导致:
        // 1. Tread.sleep
        // 2. Object.wait
        // 3. Thread.join
        // 4. LockSupport.parkNanos
        // 5. LockSupprot.parkUntil
        TIMED_WAITING,

        // 进程终止,代表进程已经执行完毕
        TERMINATED;
    }
发布了140 篇原创文章 · 获赞 2 · 访问量 1891

猜你喜欢

转载自blog.csdn.net/weixin_40602200/article/details/103948818