生产者消费者模式

public class Storage {
    private final int MAX_SIZE = 10;
    private LinkedList<Object> list = new LinkedList<>();

    public void produce() {
        while (true) {
            synchronized (list) {
                while (list.size() + 1 > MAX_SIZE) {
                    System.out.println("【生产者" + Thread.currentThread().getName() + "】仓库已满");
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.add(new Object());
                System.out.println("【生产者" + Thread.currentThread().getName() + "】生产一个产品,现库存" + list.size());
                list.notifyAll();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void consume()  {
        while (true) {
            synchronized (list) {
                while (list.size() == 0) {
                    System.out.println("【消费者" + Thread.currentThread().getName() + "】仓库为空");
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.remove();
                System.out.println("【消费者" + Thread.currentThread().getName() + "】消费一个产品,现库存" + list.size());
                list.notifyAll();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Storage s = new Storage();
        new Thread(() -> s.produce(), "p1").start();

        new Thread(() -> s.consume(), "c1").start();

        new Thread(() -> s.produce(), "p2").start();

        new Thread(() -> s.consume(), "c2").start();
  }
}
posted @ 2022-09-23 11:15  空中行走的鱼  阅读(33)  评论(0)    收藏  举报