Javaのnotify()
で少し混乱しています。次の例は、教科書の例です。Javaスレッドnotify()と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();
}
ありがとう!
よろしくお願いいたします。
ありがとう、グレー。 :-) –