线程执行完,死亡后,还能再次执行start吗?

不能

代码测试:

@Test
    public void testStart() throws InterruptedException{
        Thread add1 = new Thread(()->System.out.println("线程运行中"));
        add1.start();
        add1.join();
        add1.start();
    }

结果报异常:
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)

分析Thread源码:

 public synchronized void start() {
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    group.add(this);
    boolean started = false;
    try {
        start0();
        started = true;
        ......
 }
private void exit() {
    if (group != null) {
        group.threadTerminated(this);
        group = null;
    }
    target = null;
    threadLocals = null;
    inheritableThreadLocals = null;
    inheritedAccessControlContext = null;
    blocker = null;
    uncaughtExceptionHandler = null;
}

从上面看出,启动线程的时候,会通过threadStatus来判断线程的状态。
调用start0()时,threadStatus的值将被修改为随机的正数,从而避免
再次被启动。
而在线程死亡的时候,将内部数据置为null,而threadStatus本地方法修改为2;

你可能感兴趣的:(多线程100个问题)