Exception Handling · Introduction to Java Programming

Thread Communication

Watch lectures

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/notify INSIDE synchronized only (else IllegalMonitorStateException!).
  • wait() releases lock (others enter!). sleep() keeps lock (blocks others!).
  • while (not if) around wait (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.
  • wait vs sleep + sync rule — 5 marks, favourite traps.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules