理解线程的Wait 和 Notify

邓尼茨我今天去赶集 2021年09月03日 506次浏览
package com.exam;

public class WaitNotify {
    public static void main(String[] args) throws InterruptedException {
        final Tank tank = new Tank();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    System.out.println("Tanker: I want a tank.");
                    tank.serve(finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }
        //一个一个来
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            synchronized (tank) {
                tank.notify();
            }
        }
    }
}

class Tank {
    public void serve(int id) throws InterruptedException {
        synchronized (this) {
            this.wait();
            System.out.println("Tank: You got me.");
            Thread.sleep(1000);
            System.out.println("Tank: Who is next.");
        }
    }
}