Waiting for notification of events: using wait, notify, and notifyAll

If interdependent threads share data that’s processed alternately by them, the threads should be able to communicate with each other to notify when there’s a completion of events, or else the threads might not work correctly.

Imagine you’re waiting for your friend to go river rafting at a camp. You check whether she has arrived by peeping out of your tent every minute. This can become quite inconvenient. How about asking her to notify you when she arrives? Let’s implement this in code using the wait and notify methods from class Object. Because these methods are defined in class Object, they can be called on any Java object. Methods wait(), notify(), and notifyAll() enable threads sharing the same data to communicate with each other.

Methods wait(), notify(), and notifyAll() are defined in class Object and not in class Thread.

To call wait() or notify() a thread must own the object’s monitor lock. So calls to these methods should be placed within synchronized methods or blocks. Here’s an implementation of the previous example in code:

All overloaded versions of wait() throw a checked InterruptedException. Methods notify() and notifyAll() don’t throw an InterruptedException.

Unlike the Thread’s method join(), which waits for another thread to complete its execution, methods wait() and notify() don’t require a thread to complete their execution. The thread that calls wait(), waits for another thread to notify it using method notify() or notifyAll(). Some other examples from daily life of using wait() and notify() are teachers and students waiting to be notified for a next workshop on life skills (which can happen multiple times), an operator who answers a phone whenever she’s notified of an incoming call, or customers waiting for notification of new offers on a range of televisions.

Change in thread’s status when methods are executed from class Thread (sleep(), join(), yield()) and class Object (wait(), notify(), notifyAll())

Multiple threads might deadlock when they have acquired a lock on objects and are waiting to acquire locks on additional objects that are owned by other waiting threads. Let’s discuss this threading issue in detail next.

Code Snippet :

1)

2) if Notify is called from non-synchronized method :

Examples:

Producer And Consumer Problem :

Last updated

Was this helpful?