java 多執行緒之join 方法

2021-08-29 05:05:55 字數 2217 閱讀 1470

join()方法作用:阻塞執行緒,即等同於主線程進入子執行緒的wait()方法,等待子執行緒執行完,喚醒主線程才能繼續執行,子執行緒join到主線程。(join()只阻塞主線程,若執行緒中有其他執行緒,仍然是並行狀態)

如:main是主線程,在main中建立了thread執行緒,在main中呼叫了thread.join(),那麼等thread結束後再執行main**。(如情況二和情況三展示)

注意:雖然join只阻塞主線程,其他執行緒處於並行狀態,但前提是在主線程被阻塞之前已經開啟其他執行緒,否則主線程被阻塞,其他執行緒未被開啟,當然不存在並行的情況。

使用場景:在很多情況下,主線程中生成並啟動子執行緒,若子執行緒裡要進行大量的耗時的運算,主線程往往將於子執行緒之前執行結束,但是如果主線程處理完其他的程式後,需要用到子執行緒的處理結果,所以主線程需要等待子執行緒執行完成之後再結束,這個時候就用到join()方法。

join()方法帶參:帶引數的join()方法,即表示被阻塞執行緒等待子執行緒xx ms,join(0)等價於join()即被阻塞執行緒無限等待子執行緒。

如threadjoin.join(10),則主線程等待子執行緒10ms,就繼續執行

/**

* @description: 執行緒join方法測試

* @author: administrator

* @date: 2018/10/17

**/public class testjoin

}

/**

* @description:

* @author: administrator

* @date: 2018/10/17

**/public class threadjoin1 extends thread

public void run()

}}

情況一執行結果

testjoin main:------------------

threadjoin1 run name:plot1

threadjoin1 run name:stroy1

threadjoin1 run name:stroy2

threadjoin1 run name:stroy3

threadjoin1 run name:stroy4

threadjoin1 run name:stroy5

threadjoin1 run name:plot2

threadjoin1 run name:plot3

threadjoin1 run name:plot4

threadjoin1 run name:plot5

情況二執行結果

threadjoin1 run name:stroy1

threadjoin1 run name:stroy2

threadjoin1 run name:stroy3

threadjoin1 run name:stroy4

threadjoin1 run name:stroy5

testjoin main:------------------

threadjoin1 run name:plot1

threadjoin1 run name:plot2

threadjoin1 run name:plot3

threadjoin1 run name:plot4

threadjoin1 run name:plot5

情況三執行結果

threadjoin1 run name:stroy1

threadjoin1 run name:stroy2

threadjoin1 run name:stroy3

threadjoin1 run name:stroy4

threadjoin1 run name:stroy5

threadjoin1 run name:plot1

threadjoin1 run name:plot2

threadjoin1 run name:plot3

threadjoin1 run name:plot4

threadjoin1 run name:plot5

testjoin main:------------------

Java多執行緒之join

1.join方法只有在繼承了thread類的執行緒中才有。2.執行緒必須要start 後再join才能起作用。將另外乙個執行緒join到當前執行緒,則需要等到join進來的執行緒執行完才會繼續執行當前執行緒。package thread.join class sleeper extends thre...

多執行緒之Join方法

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

Java多執行緒join 方法詳解

今天在使用多執行緒join的時候踩了乙個坑,就是在某個執行緒內用自身呼叫join方法 這是錯誤的,仔細想想,讓自己先執行完自己的內容完然後再執行自己的內容,這不是 嗎?哈哈,所以這是錯誤的寫法 override public void run catch interruptedexception e...