使用wait/notify实现生产消费模型

public class A {
    private Deque list = new LinkedList<>();
    private int max = 10;
    private int size = 0;

    public synchronized int consumer() {
        System.out.println(Thread.currentThread().getName());
        // 不要用if
        while (size == 0) {
            try {
                System.out.println("consumer wait");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Integer integer = list.removeFirst();
        size--;
        // 可能唤醒自己所以要用notifyall
        notifyAll();
        return integer;
    }

    public synchronized void producer(int i) {
        System.out.println(Thread.currentThread().getName());
        while (size >= max) {
            try {
                System.out.println("producer wait");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(i);
        size++;
        notifyAll();
    }


    public static void main(String[] args) {
        A a = new A();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    a.consumer();
                }
            }, "consumer" + i).start();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    a.producer(j);
                }
            }, "producer" + i).start();
        }
    }
}

你可能感兴趣的:(使用wait/notify实现生产消费模型)