源码:
1 public final synchronized void join(long millis)
2 throws InterruptedException {
3 long base = System.currentTimeMillis();
4 long now = 0;
5
6 if (millis < 0) {
7 throw new IllegalArgumentException("timeout value is negative");
8 }
9
10 if (millis == 0) {
11 while (isAlive()) {
12 wait(0);
13 }
14 } else {
15 while (isAlive()) {
16 long delay = millis - now;
17 if (delay <= 0) {
18 break;
19 }
20 wait(delay);
21 now = System.currentTimeMillis() - base;
22 }
23 }
24 }
假设主线程main调用t.join()
join()内部关键代码
while (isAlive()) {//isAlive()为t线程调用,判断t线程是否还存活,为本地方法
wait(0);//该方法为主线程调用的,主线程进入等待队列
}
当t线程exit时,会通知notifyAll所有等在这个所对象上的线程,主线程就会被唤醒,再次进行while循环判断(这也是为什么要用while而不能用if的原因,因为考虑到t线程的正常唤醒),主线程跳出循环继续执行。。。