Inter-thread communication allows threads to pause, wait and resume in coordination with each other - without busy waiting.
Methods
Method | Description |
---|---|
wait() | Releases lock and waits until notified |
notify() | Wakes up one waiting thread |
notifyAll() | Wakes up all waiting thread |
These must be called within a synchronized block or method. |
Example
class Shared {
void waitForSignal() throws InterruptedException {
synchronized (this) {
System.out.println("Waiting...");
wait(); // thread goes into WAITING state
System.out.println("Notified!");
}
}
void sendSignal() {
synchronized (this) {
notify(); // wakes up one waiting thread
}
}
}
Flow
- Thread A enters synchronized block and calls
wait()
β Releases the lock and goes toWAITING
- Thread B enters the same synchronized block and calls
notify()
β Wakes Thread A - Thread A resumes execution after regaining the lock
Rules
- Must hold the monitor lock (i.e. synchronized) before calling
wait()
ornotify()
. - Throws
IllegalMonitorStateException
if called outside sync. - Always call
wait()
in a loop with a condition check (to avoid spurious wakeups).
while (!condition) {
wait();
}
Real-World Analogy
Think of wait()
as someone waiting in a line.
notify()
is the barista calling βNext!β - only one person steps forward.
Tip
Be ready to:
- write a simple Producer-Consumer example,
- explain wait() releases the lock; sleep() does not,
- know when to use notify() vs notifyAll().
Parent: _Multithreading