執行緒加入 join方法

2021-10-05 22:35:22 字數 2002 閱讀 8930

join方法用於等待其他執行緒終止

如果執行緒a中呼叫了執行緒b的join方法,那麼執行緒a阻塞,直到執行緒b執行完後,執行緒a從阻塞狀態轉為就緒狀態,等待獲取cpu的使用權。

join方法要在start方法呼叫後呼叫才有效,執行緒必須啟動,再加入。

例子1:

讓兩個執行緒順序列印1,2,3,即執行緒a列印123,執行緒a列印完後,執行緒b再列印

public

class

main

}class

jointhread

implements

runnable

}}

執行結果

例子2

public

class

main}}

class

jointhread

implements

runnable

}}

執行結果

我覺得這個main和thread1的執行順序是隨機的,主要看誰獲取了cpu的使用權。

原因:主線程呼叫t1的join方法,需要等到t1執行完再執行,t2是在t1執行完再啟動的,因此t2和main都在t1執行完後再執行,具體t2和main的執行順序要看誰獲得cpu。

例子3

public

class

main}}

class

jointhread

implements

runnable

}}

執行結果

這裡,main和thread-1的執行順序就很隨機了。

例子4

public

class

main}}

class

jointhread

implements

runnable

}}

執行結果

這個例子就可以很明顯看出,呼叫t1的join方法的是main執行緒,t1和t2隨機執行,t2和main的執行順序應該也是隨機的,但main在t1完成之後執行。

原始碼

public

final

synchronized

void

join

(long millis)

throws interruptedexception

if(millis ==0)

}else

wait

(delay)

; now = system.

currenttimemillis()

- base;}}

}

join方法是通過呼叫執行緒的wait方法來達到同步的目的。

join方法是呼叫相應執行緒的wait方法進行等待操作,比如執行緒a呼叫了執行緒b的join方法,相當於呼叫了執行緒b的wait方法,當執行緒b執行完後(或到達等待時間),執行緒b自動呼叫自身的notifyall方法喚醒執行緒a。

join()就等於join(0)不設等待時間,直到被呼叫join的執行緒執行完。

參考資料

多執行緒Join方法

天意憐幽草,人間重晩晴 a.sleep 5000 讓執行緒睡5秒但是,如果你不知道執行緒b需要執行多長時間,並且在a中需要使用到b中的結果,那麼,這時你就可以使用join方法 下面是具體的例子 可以看到,join long time 方法內部其實是呼叫了wait long time 方法,我們了解到...

多執行緒join 方法

直接 public static void main string args for thread t list int n 0 for thread t list catch interruptedexception e system.out.println 完全結束 static class m...

多執行緒之Join方法

執行緒加入 join 方法,等待其他執行緒終止。在當前執行緒中呼叫另乙個執行緒的join 方法,則當前執行緒轉入阻塞狀態,直到另乙個程序執行結束,當前執行緒再由阻塞轉為就緒狀態。package thread public class threadjointest class threadjoin i...