我为什么都是10个一起的 运行了几次都一样。代码是下载的
来源:7-6 用wait/notify实现

poisonSky
2019-08-29
写回答
1回答
-
这个不是每次都必现,我刚运行了几次,肯定是会出现非10个一起的情况的:
代码如下:
/** * 描述: 用wait/notify来实现生产者消费者模式 */ public class ProducerConsumerModel { public static void main(String[] args) { EventStorage eventStorage = new EventStorage(); Producer producer = new Producer(eventStorage); Consumer consumer = new Consumer(eventStorage); new Thread(producer).start(); new Thread(consumer).start(); } } class Producer implements Runnable { private EventStorage storage; public Producer( EventStorage storage) { this.storage = storage; } @Override public void run() { for (int i = 0; i < 100; i++) { storage.put(); } } } class Consumer implements Runnable { private EventStorage storage; public Consumer( EventStorage storage) { this.storage = storage; } @Override public void run() { for (int i = 0; i < 100; i++) { storage.take(); } } } class EventStorage { private int maxSize; private LinkedList<Date> storage; public EventStorage() { maxSize = 10; storage = new LinkedList<>(); } public synchronized void put() { while (storage.size() == maxSize) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } storage.add(new Date()); System.out.println("仓库里有了" + storage.size() + "个产品。"); notify(); } public synchronized void take() { while (storage.size() == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("拿到了" + storage.poll() + ",现在仓库还剩下" + storage.size()); notify(); } }
032020-03-30
相似问题