1、join()方法的作用:
例如有一个线程对象为Thread1,在main()方法中调用Thread1.join()方法可使得当前线程(即主线程)阻塞,而执行Thread1线程。
2、源码分析(以上面的例子为例)
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis (等待时间为毫秒)
* the time to wait in milliseconds
*
* @throws IllegalArgumentException (当 millis 为负数时抛出此异常)
* if the value of {@code millis} is negative
*
* @throws InterruptedException (如果有任何线程中断了当前线程(当前线程为main线程),抛出此异常,当前线程的中断状态将被清除。该异常由源码中的wait()抛出)
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
//这段代码是由main线程执行的
public final void join(long millis) throws InterruptedException {
synchronized(lock) { //这里的lock是在Thread1中创建的,源码为 private final Object lock=new Object();
//main线程获取对象lock的锁
long base = System.currentTimeMillis();//获取系统当前时间毫秒值
long now = 0; //表示等待了多少时间 if (millis < 0) { //抛出 millis 为负数的异常
throw new IllegalArgumentException("timeout value is negative");
} if (millis == 0) { //毫秒值为零,意味着等待到Thread1结束
while (isAlive()) { //当Thread1线程还活着时
lock.wait(0); //使得拥有lock对象的锁的线程(main线程)停止,并使得当前线程释放锁,那什么时候调用notifyAll呢?这个答案在 jvm源码中,在此不细述
} //中断异常也是由wait()方法抛出
} else { //否则,等待millis
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break; // 等待时间结束,跳出了join()方法,main线程继续执行
}
lock.wait(delay); //延时等待
now = System.currentTimeMillis() - base; //更新now
}
}
}
}