More advanced synchronization can be accomplished using the
notifyAll() methods of the
Object class. You can use these methods to cause threads to wait until an object is updated by another thread.
As an example, consider the situation where an object supports Consumer and Producer
threads. Consumer threads consume information provided by the object.
Producer threads produce information that is provided to the object. Consumers wait until Producers update the object's information before consuming that information.
methods are used by Consumers and Producers as follows:
- A Consumer thread invokes a synchronized method of an object and acquires the object's lock. The synchronized method tests to see if the object has been updated. If not, the object's
wait() method is invoked.
This causes the thread to lose the object's lock and wait until the object has been updated.
- A Producer thread updates the object and invokes the object's
notifyAll() methods. The
notify() method causes a waiting Consumer thread to be returned to the ready state.
notifyAll() method causes "all of the Consumer threads" to be returned to the ready state.
- When a waiting Consumer thread reenters the running state, it reacquires the lock on the object and can then continue its processing and consume the object's resources .
An object typically implements the
methods using synchronized methods of the following form: