一、join()方法的做用:app
例若有一個線程對象爲Thread1,在main()方法中調用Thread1.join()方法可以使得當前線程(即主線程)阻塞,而執行Thread1線程。jvm
二、源碼分析(以上面的例子爲例)oop
/**
* 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 } } } }