wait(), notify(), and notifyAll() methods on the certification exam
You can expect to see questions about the
wait()
,
notify()
, and
notifyAll()
methods on the certification exam. You should be able to examine code that uses these methods and determine when a particular thread will acquire an object's lock, execute a synchronized method, and relinquish the object's lock.
You should also be able to determine when one thread will wait for another and when the other thread will notify the first that it is able to continue its processing. These questions will very likely be multiple choice questions about a small code sample.
Object has Associated Lock
Just as every Java object has a lock associated with it, every object maintains a list of waiting threads. When a thread calls the wait() method of an object, any locks the
thread holds are temporarily released, and the thread is added to the list of waiting threads for that object and stops running.
When another thread calls the notifyAll()
method of the same object, the object wakes up the waiting threads and allows them to continue running.
wait() and notify() must be used inside a synchronized method or block, because of the temporary relinquishing of locks that is required for them to work properly.