Using wait(), notify() and notifyAll()

The Java language includes three important methods that effectively allow one thread to signal to another. Without this facility, various constructs used in concurrent programming would be difficult and inefficient to implement, at least prior to Java 5 (see below).

Put simply, this is how signalling between threads works using 'wait and notify':

In some of the following discussion, we'll use the term wait/notify mechanism, and refer to the two methods wait() and notify(). However, we'll see that much of the discussion includes notifyAll() and we'll look at when to use the two variants below.

How to use wait/notifty?

The following issues then generally arise:

See also: common bugs with wait/notify.

The wait()/notify() construct in Java 5

In Java 5, it's less common to need to call wait() and notify() explicitly. This is because various library classes implement the types of object that typically use wait()/notify() mechanism. For more information, see:

Further recommended reading

This site actually covers much of the information you are likely to need about wait()/notify() and related synchronization and concurrency issues in Java. However, it is also recommended that you check out the following:

Goetz, B. et al, Java Concurrency in Practice
A clearly written, authoritative guide to the modern concurrency features and libraries in Java. This book is likely to become something of a bible for anybody serious about issues of synchronization and concurrent programming in Java. In particular, this book gives good (and comprehensible!) coverage of the Java memory model, and much better coverage of the new Java 5 and 6 concurrency features than many other publications.
Bloch, J. Effective Java (2nd Edition)
A valuable resource for programmers of all levels. See in particular the chapter on Concurrency and Item #69: "Prefer concurrency utilities to wait and notify".
Oaks, S Java Threads
Another good resource on multithreading in Java. See Chapter 4 on Thread Notification, plus other sections such as Chapter 11 on Task Scheduling for coverage of certain Java 5 concurrency features.