基於Java多線程notify與notifyall的差別剖析。本站提示廣大學習愛好者:(基於Java多線程notify與notifyall的差別剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是基於Java多線程notify與notifyall的差別剖析正文
當一個線程進入wait以後,就必需等其他線程notify/notifyall,應用notifyall,可以叫醒
一切處於wait狀況的線程,使其從新進入鎖的爭取隊列中,而notify只能叫醒一個。留意,任什麼時候候只要一個線程可以取得鎖,也就是說只要一個線程可以運轉synchronized 中的代碼,notifyall只是讓處於wait的線程從新具有鎖的爭取權,然則只會有一個取得鎖並履行。
那末notify和notifyall在後果上又甚麼本質差別呢?
重要的後果差別是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