线程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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值