在这里,我尝试在线程终止后加入该线程,代码工作正常,但我的问题是它不应该抛出一些错误消息或任何信息吗?
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");
}
}
最佳答案
如果你查看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;
}
}
...
因此,如果您调用 join
的线程被终止 - join
将返回并且不执行任何操作。
关于java - 如果我加入已终止(死亡)的线程怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544672/