代码一:
public static void main(String[] args) throws Exception {
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(10);
System.out.println("thread-0 thread exit.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "thread-0");
thread.start();
thread.join();
System.out.println("main thread exit.");
}
控制台(10s后打印并退出):
thread-0 thread exit.
main thread exit.
Process finished with exit code 0
代码二:
public static void main(String[] args) throws Exception {
Thread.currentThread().join();
System.out.println("main thread exit.");
}
控制台(一直等待中):
问题:第一段代码是main
线程阻塞在thread-0
线程上,当thread-0
执行完毕,main
线程也同时退出,那第二段代码中main
线程阻塞在哪个线程上呢,为什么没有退出?
探究
为了了解问题本质,我们跟进去代码看看,线程的join方法如下:
再继续跟:
根据代码,其实join方法最终是待用了wait(0);这行代码,而wait方法是本地方法.
根据wait的方法定义,有以下几点逐一说明:
throws InterruptedException`,因此调用wait方法后,实际上是获取了当前对象(根据调试查看到是main线程)的监视器.
总结
因此,回答你的问题就是,join方法实质是调用了wait方法.wait方法调用后阻塞(我不认为这是阻塞)在当前线程(main线程上),根据wait的定义,不调用notify,notifyAll,interrupt以及超时机制(本例调用的是wait(0),故不存在这种情况),那么线程将一直处于等待状态,故一直不会退出。