Inter-thread communication allows threads to pause, wait and resume in coordination with each other - without busy waiting.

Methods

MethodDescription
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

  1. Thread A enters synchronized block and calls wait()
    β†’ Releases the lock and goes to WAITING
  2. Thread B enters the same synchronized block and calls notify()
    β†’ Wakes Thread A
  3. Thread A resumes execution after regaining the lock

Rules

  • Must hold the monitor lock (i.e. synchronized) before calling wait() or notify().
  • 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