Java Thread Wait & Notify

In Java, wait() and notify() are two methods defined in the Object class used to implement collaboration and communication between threads. These methods must be invoked within a synchronized block. Their functions are as follows:

  1. wait() method: Puts the current thread into a waiting state, releases the object lock, and waits for another thread to call either the notify() or notifyAll() method to wake it up. The wait() method has two forms:

    • public final void wait() throws InterruptedException: Puts the current thread into a waiting state until it is awakened by another thread calling the notify() or notifyAll() method, or unless an InterruptedException exception is thrown because the current thread was interrupted.
    • public final void wait(long timeout) throws InterruptedException: Puts the current thread into a waiting state for at most timeout milliseconds; if not awakened within this time period, it will automatically resume execution.
  2. notify() method: Wakes up one of the threads currently waiting on the object. If multiple threads are waiting, only one is chosen to be woken up; however, which specific thread is selected is unpredictable. The notify() method can only be called within a synchronized block and must first acquire the object lock.

Using the wait() and notify() methods enables collaboration and communication between threads, where wait() handles waiting and releasing locks while notify() handles waking up waiting threads. Typically, the usage of these two methods follows these guidelines:

  • Within a synchronized block, use a while loop to wait for condition satisfaction rather than an if statement to avoid spurious wakeups.
  • When the condition is satisfied, call the notify() method to awaken the waiting thread(s).
  • After awakening a waiting thread, re-evaluate whether the condition is still met; if not, continue to wait.
  • In both wait() and notify() methods, use synchronized blocks to protect object state from race conditions and consistency issues caused by multi-threaded access.

It should be noted that the wait() and notify() methods must be used within a synchronized block because they require acquiring an object lock to facilitate inter-thread communication. Furthermore, the order of calling these two methods is critical; otherwise, deadlocks or thread starvation may occur. Therefore, when using the wait() and notify() methods, it is essential to carefully design the collaboration and communication mechanisms between threads to ensure program correctness and reliability.