The Object.wait()
method temporarily cedes possession of a lock so that another thread that is requesting the lock can proceed. Object.wait()
must always be called from a synchronized block or method. To resume the waiting thread, the requesting thread must invoke the notify()
method to notify it. Furthermore, the wait()
method should be invoked in a loop that checks if a condition predicate holds. Note that a condition predicate is the negation of the condition expression in the loop. For example, the condition predicate for removing an element from a vector is !isEmpty()
, whereas the condition expression for the while loop condition is isEmpty()
. The correct way to invoke the wait()
method when the vector is empty is shown below.
Code Block |
---|
private Vector vector; //... public void consumeElement() throws InterruptedException { synchronized (vector) { while (vector.isEmpty()) { vector.wait(); } // Consume when condition holds } } |
The notification mechanism notifies the waiting thread and lets it check its condition predicate. The invocation of notify()
or notifyAll()
in another thread cannot precisely determine which waiting thread is resumed. A condition predicate statement is provided so that only the correct thread will resume upon receiving the notification. A condition predicate also helps when a thread is required to block until a condition becomes true, such as reading data from an input stream before proceeding.
...