如果我加入已终止(死亡)的线程怎么办

She*_*lly 2 java multithreading java-threads

在这里,我试图在线程终止后加入该线程,代码工作正常,但我的问题是它不应该抛出一些错误消息或任何信息吗?

public class MultiThreadJoinTest implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(new MultiThreadJoinTest());
        a.start();
        Thread.sleep(5000);
        System.out.println("Begin");   
        System.out.println("End");
        a.join();
    }

    public void run() {
        System.out.println("Run");
    }
}
Run Code Online (Sandbox Code Playgroud)

mic*_*alk 5

如果您查看源代码,Thread::join您会发现它调用了Thread::join(timeout)方法。查看该方法的源代码,我们可以看到它通过调用循环检查线程的状态Thread::isAlive

...
if (millis == 0 L) {
    while (this.isAlive()) {
        this.wait(0 L);
    }
} else {
    while (this.isAlive()) {
        long delay = millis - now;
        if (delay <= 0 L) {
            break;
        }

        this.wait(delay);
        now = System.currentTimeMillis() - base;
    }
}
...
Run Code Online (Sandbox Code Playgroud)

因此,如果您调用的线程join被终止 -join将返回并且不执行任何操作。