【Java基础】生产者消费者模式
很多项目后台逻辑实际上就是生产者消费者的关系,实现生产者消费者的方式有很多中,去泰国每天要喝至少三杯芒果冰沙,就拿制作芒果冰沙为例子,商家是生产者,我是消费者,可能同时有很多个消费者,1.要保证生产的芒果冰沙有柜台可以放的下,设置最大能放100杯;2.当柜台上芒果冰沙数为0时,消费者需要等待:
/** * Created by zw on 2019/5/15. * 存放芒果冰沙 */ public class Storage { private final int MAX_SIZE = 100; private LinkedList<MangoIce> mangoIceLinkedList = new LinkedList<>(); public void produce(){ synchronized (mangoIceLinkedList){ //如果仓库满了 if(mangoIceLinkedList.size() + 1 > MAX_SIZE){ try { mangoIceLinkedList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { mangoIceLinkedList.add(new MangoIce()); System.out.println("【目前剩余的冰沙数】:" + mangoIceLinkedList.size()); mangoIceLinkedList.notifyAll(); } } } public void consume(){ synchronized (mangoIceLinkedList){ //如果仓库为空 不用消费 if(mangoIceLinkedList.size() == 0){ try { mangoIceLinkedList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { mangoIceLinkedList.remove(); System.out.println("【目前消费后的冰沙数】:" + mangoIceLinkedList.size()); mangoIceLinkedList.notifyAll(); } } } public static void main(String[] args) { Storage storage = new Storage(); Producer producer = new Producer(storage); Producer producerB = new Producer(storage); Producer producerC = new Producer(storage); Producer producerD = new Producer(storage); Producer producerE = new Producer(storage); Consumer consumer = new Consumer(storage); Consumer consumerB = new Consumer(storage); producer.start(); consumer.start(); producerB.start(); consumerB.start(); producerC.start(); producerD.start(); producerE.start(); } } /** * Created by zw on 2019/5/15. * 生产者 */ public class Producer extends Thread{ private Storage storage; public Producer(Storage storage){ this.storage = storage; } @Override public void run() { storage.produce(); } } /** * Created by zw on 2019/5/15. * 消费者 */ public class Consumer extends Thread { private Storage storage; public Consumer(Storage storage){ this.storage = storage; } @Override public void run() { storage.consume(); } }
欢迎关注Java流水账公众号