ProLesson 9.5Advanced3 min readUpdated 30 October 2026
wait and notify
How threads signal each other with wait, notify and notifyAll, a producer-consumer example, and why modern code uses BlockingQueue instead.
Sometimes a thread must wait until something happens: a consumer waits until there's an order to process, a producer waits until there's space. Java's original tools for this are wait(), notify() and notifyAll(), methods on every Object. You'll rarely write them today, but interviewers love them.
01The rules
wait(),notify()andnotifyAll()must be called while holding the object's lock, insidesynchronized (obj). Otherwise you getIllegalMonitorStateException.wait()releases the lock and sleeps until another thread callsnotifyornotifyAllon the same object.notify()wakes one waiting thread;notifyAll()wakes all of them.- Always call
wait()inside a loop that re-checks the condition, because a thread can wake up without its condition being true (a "spurious wakeup", or another thread got there first).
Loading the rest of the lesson…