Thread Communication
1. Why Talk? (beginner)
Threads share work: producer makes, consumer eats. Without talk: consumer spins (wastes CPU!) or misses items! wait() / notify() = sleep-until signal (efficient queue!).
2. Code — Shop Queue (exam classic!)
class Shop {
int bread = 0;
synchronized void bake() { // producer!
bread++;
System.out.println("baked: " + bread);
notify(); // wake one waiter!
}
synchronized void eat() throws InterruptedException {
while (bread == 0) wait(); // SLEEP (releases lock!) until bake notifies!
bread--;
System.out.println("eaten, left: " + bread);
}
}
// producer: bake() → notify! consumer: wait() → wake → eat!
3. Rules (exam traps!)
wait/notifyINSIDEsynchronizedonly (elseIllegalMonitorStateException!).wait()releases lock (others enter!).sleep()keeps lock (blocks others!).while(notif) aroundwait(spurious wakeups!).notifyAll()wakes all (many consumers!).
4. Methods Table
| Method | Job |
|---|---|
wait() |
sleep + release lock (until notify!) |
notify() |
wake ONE waiter |
notifyAll() |
wake ALL (safest!) |
Modern alt: BlockingQueue (no manual wait/notify!).
5. Exam Points
- Producer-consumer program — 7 marks, very frequent.
waitvssleep+ sync rule — 5 marks, favourite traps.