Thread.start()方法解析


一、线程的六种状态

线程的所有状态都在Thread中的State类中定义,如下所示:

public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;
}

详情请见下图:
在这里插入图片描述

注意:从NEW状态出发后,线程不能回到NEW状态,同理,处于TERMINATED状态的线程也不能回到RUNNABLE状态。

二、Thread.start()源码

public synchronized void start() {
	//NEW状态的threadStatus=0,不为NEW状态抛出异常!
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
     //添加到ThreadGroup中
    group.add(this);
    boolean started = false;
    try {
        start0();
        //设置started标记=true
        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 */
        }
    }
}

start0()方法源码

private native void start0();

Thread.start()会调用本地方法start0()启动新线程并让这个线程执行run()方法。

run()方法源码

public void run() {
    if (target != null) {
        target.run();
    }
}

注意: 1.通过继承Thread类,重写run()方法创建新的线程,直接执行重写的run()方法。

​2.实现Runnable接口,重写run()方法创建新的线程,通过Thread.run()方法调用重写的run()方法。

三、问题:一个线程中的Thread.start()方法能多次执行吗?

从上面的Thread.start()源码可以看出,当线程的状态不为NEW时,调用start()方法将抛出异常!线程从NEW状态出发,不能再回到NEW状态。因此,一个线程中的Thread.start()只能执行一次,不能多次执行。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值