1. 程式人生 > >Thread.join()的真正含義

Thread.join()的真正含義

首先, Thread.join() 並沒有將執行緒合併起來~
任何疑惑都先從Java Doc開始,
這裡寫圖片描述

stackoverflow上有個極好的例子:
這裡寫圖片描述
1. After the main thread creates and starts the t1 and t2 threads. There are 3 threads running in parallel: main, t1, t2
2, The main thread calls t1.join() to wait for the t1 thread to finish.
3. The t1 thread completes and the t1.join() method returns in the main thread. Note that t1 could already have finished before the join() call is made in which case the join()call will return immediately.
4. The main thread calls t2.join() to wait for the t2 thread to finish.
5. The t2 thread completes (or it might have completed before the t1 thread did) and the t2.join() method returns in the main thread.
雖然main, t1, t2都在runing, 但是到了t1.join()這句話開始,main必須等待t1, t2執行結束後才可以往下執行
舉個栗子,
這裡寫圖片描述


倘若t沒有執行結束, 那麼main就會一直阻塞在”t.join()“這裡。
倘若將t.join()註釋掉,就可以執行結束。執行效果如下:
這裡寫圖片描述

回到最上面的栗子(灰顏色程式碼)
執行緒t1, t2可以在main()呼叫join()函式之前執行結束。這時候,join() will not wait but will return immediately.

還有一點,很重要: t1.join() means cause t2 to stop until t1 terminates?
No. The main thread that is calling t1.join() will stop running and wait for the t1 thread to finish. The t2 thread is running in parallel and is not affected by t1 or the t1.join() call at all.
所以這時候可能出現一下情況,
這裡寫圖片描述

In terms of the try/catch, the join() throws InterruptedException meaning that the main thread that is calling join() may itself be interrupted by another thread.

說人話,線上程t中呼叫了另外一個執行緒innerThread.join(), 倘若這時候執行緒t受到外部的影響,比如 interrupted by main thread中的”t.interrupt()”, 此時 innerThread.join()會丟擲異常InterruptedException,此時執行緒t需要處理這個異常。然而,並不影響執行緒innerThread的執行的。請看下面的例子:
這裡寫圖片描述


執行結果如下:
這裡寫圖片描述
innerThread丟擲異常並沒有影響到它本身的執行。

而在main()執行緒中呼叫了t.interruput×()導致了執行緒t接收到了來自innerThread丟擲異常,符合Thread.interrupt()的定義。
這裡寫圖片描述

這裡寫圖片描述