基于Java多線程notify與notifyall的區(qū)別分析
當一個線程進入wait之后,就必須等其他線程notify/notifyall,使用notifyall,可以喚醒
所有處于wait狀態(tài)的線程,使其重新進入鎖的爭奪隊列中,而notify只能喚醒一個。注意,任何時候只有一個線程可以獲得鎖,也就是說只有一個線程可以運行synchronized 中的代碼,notifyall只是讓處于wait的線程重新?lián)碛墟i的爭奪權(quán),但是只會有一個獲得鎖并執(zhí)行。
那么notify和notifyall在效果上又什么實質(zhì)區(qū)別呢?
主要的效果區(qū)別是notify用得不好容易導致死鎖,例如下面提到的例子。
public synchronized void put(Object o) {
while (buf.size()==MAX_SIZE) {
wait(); // called if the buffer is full (try/catch removed for brevity)
}
buf.add(o);
notify(); // called in case there are any getters or putters waiting
}
public synchronized Object get() {
// Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)
while (buf.size()==0) {
wait(); // called if the buffer is empty (try/catch removed for brevity)
// X: this is where C1 tries to re-acquire the lock (see below)
}
Object o = buf.remove(0);
notify(); // called if there are any getters or putters waiting
return o;
}
所以除非你非常確定notify沒有問題,大部分情況還是是用notifyall。
更多詳細的介紹可以參看:
http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again
- java 多線程Thread與runnable的區(qū)別
- java創(chuàng)建線程的兩種方法區(qū)別
- Java線程池的幾種實現(xiàn)方法和區(qū)別介紹實例詳解
- java 線程詳解及線程與進程的區(qū)別
- java 線程中start方法與run方法的區(qū)別詳細介紹
- Java線程池的幾種實現(xiàn)方法和區(qū)別介紹
- java中thread線程start和run的區(qū)別
- java基本教程之Thread中start()和run()的區(qū)別 java多線程教程
- Java線程中sleep和wait的區(qū)別詳細介紹
- 詳解多線程及Runable 和Thread的區(qū)別
相關(guān)文章
詳解mybatis plus使用insert沒有返回主鍵的處理
這篇文章主要介紹了詳解mybatis plus使用insert沒有返回主鍵的處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09Spring Boot部署到Tomcat過程中遇到的問題匯總
這篇文章主要給大家分享了關(guān)于Spring Boot部署到Tomcat過程中遇到的一些問題,文中將解決的方法介紹非常詳細,對同樣遇到這個問題的朋友具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-03-03