The wait and notify mechanisms in Java are fundamental tools for inter-thread communication. They are used to coordinate the activities of threads that share a common resource. Here’s an in-depth look at how these mechanisms work, along with a practical example.
Basics of wait and notify
wait():
The wait() method is used by a thread to release the lock it holds on an object and enter the waiting state.
The thread remains in the waiting state until another thread calls notify() or notifyAll() on the same object.
This method must be called from within a synchronized block or method, ensuring the thread holds the object’s monitor when it calls wait().
notify():
The notify() method wakes up a single thread that is waiting on the object’s monitor. If multiple threads are waiting, one is chosen to be awakened (the choice is arbitrary and depends on the JVM implementation).Like wait(), notify() must also be called from within a synchronized block or method.
notifyAll():
The notifyAll() method wakes up all threads that are waiting on the object’s monitor. The awakened threads will compete to acquire the lock.
// Defined in java.lang.Object
public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
public final void notify()
public final void notifyAll()
Code language: PHP (php)