The Object.wait()
method is used to temporarily cede possession of a lock so that another requesting thread can proceed. It must always be used inside a synchronized
block or method. To resume activity, the requesting thread must notify the waiting thread. Moreover, the wait()
method should be invoked in a loop that checks if a condition predicate holds.
The invocation of notify()
or notifyAll()
in another thread cannot precisely determine which waiting thread must be resumed. A condition predicate statement is used so that the correct thread resumes when it receives a notification. A condition predicate also helps when a thread is required to block until a condition becomes true, for instance, when it cannot proceed without obtaining some data from an input stream.
...
Code Block | ||
---|---|---|
| ||
// ConditionThe condition predicate is guarded byguards a lock on the shared object/variable synchronized (object) { while (<condition does not hold>) { object.wait(); } // Proceed when condition holds } |
...