我很困惑Java的notify()
。以下示例來自教科書。Java線程通知()與notifyAll()
public synchronized consume() {
while(queue.isEmpty()) {
try{ wait(); } catch (InterruptedException e) {}
}
// Assume that getElement() notifies to producers.
element = queue.getElement();
...
}
public synchronized produce() {
while(queue.isFull()) {
try{ wait(); } catch (InterruptedException e) {}
}
element = new Element();
...
queue.addElement(element);
notifyAll();
}
我很理解上面例子中的方法produce()
。然而,誰能告訴我爲什麼我們在第一種方法(consume()
)結束時不使用notifyAll()
?簡而言之,爲什麼不這樣:
public synchronized consume() {
while(queue.isEmpty()) {
try{ wait(); } catch (InterruptedException e) {}
}
// Assume that getElement() notifies to producers.
element = queue.getElement();
...
notifyAll();
}
非常感謝!
此致敬禮。
非常感謝,格雷。 :-) – 2012-04-12 02:47:04