Ich bin ein wenig verwirrt von Java notify()
. Das folgende Beispiel stammt aus einem Lehrbuch.Java Thread notify() vs. 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();
}
Ich verstehe durchaus die Methode produce()
in dem obigen Beispiel. Kann mir aber jemand sagen, warum wir notifyAll()
am Ende der ersten Methode (consume()
) nicht verwenden? Kurz, warum nicht wie folgt:
public synchronized consume() {
while(queue.isEmpty()) {
try{ wait(); } catch (InterruptedException e) {}
}
// Assume that getElement() notifies to producers.
element = queue.getElement();
...
notifyAll();
}
Vielen Dank!
Mit freundlichen Grüßen.
Vielen Dank, Grey. :-) –