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':
- We can call the wait() method of any Java object, which suspends
the current thread. The thread is said to be "waiting on" the given object.
- Another thread calls the notify() method of the same Java object.
This "wakes up" one of the threads waiting on that object.
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.