Java Thread wait notify

Synchronization Control in the Object Class

  • final void wait()
    • Makes a thread wait until notify() or notifyAll() is called.
    • Releases the lock in the synchronized area and moves the thread to the Wait-Set area, which exists for each shared object.
  • final void wait(long timeout)
    • Timeout version of wait().
  • final void notify()
    • Resumes one thread waiting on this object. The thread to resume cannot be selected.
    • Wakes a thread in the Wait-Set area so that it can run.
    • notify() wakes an arbitrary thread, so it may wake a thread other than the one you intended.
  • final void notifyAll()
    • Resumes all threads waiting on this object.
    • notifyAll() wakes all threads in the Wait-Set.
  • wait, notify, and notifyAll can all be executed only inside a synchronized area.
  • These methods are provided by the Object class.
package com.devkuma.basic.thread.wait;

public class ThreadA extends Thread {
    // When this thread runs, it acquires its own monitor lock.
    // It repeats 5 times, sleeps for 0.5 seconds each time, and accumulates values in total.
    // After that, it calls notify() to wake the waiting thread.
    int total;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 5; i++) {
                System.out.println(i + "를 더합니다.");
                total += i;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            notify();
        }
    }

    public static void main(String[] args) {
        // Create thread A and start it.
        // When this thread runs, it acquires its own monitor lock inside the run method.
        ThreadA a = new ThreadA();
        a.start();

        // Set a synchronized block for a.
        // If the main thread executes the block below before ThreadA, it waits and releases the monitor lock.
        synchronized (a) {
            try {
                // Call the a.wait() method.
                // The main thread stops.
                // When ThreadA adds values 5 times and calls notify, it wakes from wait.
                System.out.println("b가 완료될때까지 기다립니다.");
                a.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Print the result after waking.
            System.out.println("Total is: " + a.total);
        }
    }
}