Notify And Wait

Wait

The wait() keyword only works in a synchronised block. If it's outside of the synchronized block, it simply do nothing.

Purpose: waiting indefinitely for a resource — specified by synchronised statement. When some thread called notify() or notifyAll(), it will unblock the wait() and continue executing the code.

Notify

notify() or notifyAll() only works in a synchronised block and there is a resource that's waiting.

  • notify(): notify a random resource that called wait() first
  • notifyAll(): notify all resource that called wait()

Example

package multithreads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WaitAndNotifyDemo {
    public static void main(String[] args) {
        Game game = new Game();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(() -> {
            try {
                game.player1();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        executorService.submit(() -> {
            try {
                game.player2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        executorService.shutdown();
    }
}

class Game {
    public void player1() throws InterruptedException {
        System.out.println("Player 1: Waiting for player 2 to be ready");
        synchronized (this) {
            wait();
            System.out.println("Player 1: Done");
        }
        System.out.println("Player 1: Started the game");
    }

    public void player2() throws InterruptedException {
        Thread.sleep(1000); // IMPORTANT: make sure player1 called wait() first
        synchronized (this) {
            System.out.println("Player 2: Preparing the game");
            Thread.sleep(2000);
            notify();
            System.out.println("Player 2: Releasing this lock");
        }
    }
}