模拟生产者、消费者 一个生产者、一个消费者、仓库容量为1,模拟生产者、消费者通信过程。 思路: 仓库:ArrayList,初始化大小为1。 生产者:当仓库未满的情况下,进行生产,并通知消费者消费;当仓库是满的时候,等待消费者消费后的通知。 消费者:当仓库中不为空的情况下,进行消费,并通知生产者生产;当仓库为空时,等待生产者生产后的通知。 实现: public class ProducerConsumer0416 { //生产者 static class Producer implements Runnable{ ArrayList<Integer> arrayList;//仓库 int NUM = 20;//生产的次数 public Producer(ArrayList<Integer> arrayList){ this.arrayList = arrayList; } @Override public void run() { while (NUM -- > 0) { synchronized (arrayList){ //判断仓库是否满了,指定仓库大小为1,所以这里只用给定大小 if (arrayList.size() < 1){ //未满,生产 arrayList.add(1); System.out.println("正在生产"); arrayList.notify();//通知消费者消费 }else { try { arrayList.wait();//满了,则等待 } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //消费者