In multithreaded Java programs, the wait() method allows a thread to pause execution until another thread delivers a notification via notify() or notifyAll(). These methods must be invoked inside a synchronized context on the same monitor object.
Sequence of Operations
flowchart TD
A[Acquire Monitor Lock] --> B[Thread Invokes wait]
B --> C[Thread Enters Wait Set]
D[Another Thread Acquires Same Lock] --> E[Invokes notify/notifyAll]
E --> F[Waiting Thread Exits Wait Set]
F --> G[Re-acquires Lock and Proceeds]
Practical Steps
| Step | Action |
|---|---|
| 1 | Create a shared monitor object |
| 2 | Inside a synchronized block, call wait() |
| 3 | From another thread, call notify() or notifyAll() on the same monitor |
1. Defining the Monitor Lock
Object monitor = new Object();
This instance acts as the coordination point; threads synchronize on it and use it to wait or wake up.
2. Suspending a Thread with wait
synchronized (monitor) {
try {
monitor.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Calling wait() releases the monitor lock and moves the thread to the wait set. Once notified, it must reacqurie the lock before continuign.
3. Waking Threads from Another Context
synchronized (monitor) {
monitor.notify(); // wakes one waiting thread
// or
// monitor.notifyAll(); // wakes all waiting threads
}
Relationship Diagram
classDiagram
class Monitor {
+wait()
+notify()
+notifyAll()
}
class WaitingThread {
+run()
}
class NotifierThread {
+run()
}
Monitor <.. WaitingThread : synchronized
Monitor <.. NotifierThread : synchronized
Always guard wait and notify calls with a conditional loop to protect against spurious wakeups:
synchronized (monitor) {
while (conditionNotMet) {
monitor.wait();
}
// proceed when condition is satisfied
}