join方法的原理
就是调用相应线程的wait方法进行等待操作的,假如线程1中调用了线程2的join方法,则相当于在线程1中调用了线程2的wait方法,当线程2执行完(或者到达等待时间),线程2会自动调用自身的notifyAll方法唤醒线程1,从而达到同步的目的。
例子
一、如线程1调用线程2的join方法,即线程2.join(0);(需要注意的是,jdk规定,join(0)的意思不是线程1等待线程2 零秒,而是线程1等待线程2无限时间,直到B线程执行完毕,即join(0)等价于join()。)
二、如线程1调用线程2的join方法,即线程2.join(3);(表示线程1等待线程2 三秒,三秒过后线程和线程并行执行)
join函数源码
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 }