概述
根据jdk官方API的定义:
Thread.join方法是阻塞调用线程(也称阻塞主线程),待被调用线程(子线程)运行结束后主线程才会被唤醒。 通常用在main方法中。
替代方案
jdk1.7 CountDownLatch
join底层实现原理
wait、notify机制,可以深入的查看底层实现源码:
/**
2
* Waits at most <code>millis</code> milliseconds for this thread to
3
* die. A timeout of <code>0</code> means to wait forever.
4
*/
5
//此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。
6
public
final
synchronized
void
join(
long
millis)
throws
InterruptedException {
7
long
base = System.currentTimeMillis();
8
long
now = 0;
9
10
if
(millis < 0) {
11
throw
new
IllegalArgumentException("timeout value is negative");
12
}
13
14
if
(millis == 0) {
15
while
(isAlive()) {
16
wait(0);
17
}
18
}
else
{
19
while
(isAlive()) {
20
long
delay = millis - now;
21
if
(delay <= 0) {
22
break
;
23
}
24
wait(delay);
25
now = System.currentTimeMillis() - base;
26
}
27
}
28
}