Day22
一、仓储模型
知识点:仓储模型
需求:
生产者线程不断的生产面包放入仓库
消费者线程不断的从仓库中取出面包
做到先生产的面包先卖出分析:
生产者线程、消费者线程、面包类、仓库类
先生产的面包先卖出 – 队列模式(LinkedList)场景:一个生产者,一个消费者
public class Cake { private String brand; private String datetime; public Cake(String brand, String datetime) { this.brand = brand; this.datetime = datetime; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getDatetime() { return datetime; } public void setDatetime(String datetime) { this.datetime = datetime; } @Override public String toString() { return brand + " -- " + datetime; } } public class Store { private static final int MAX_INIT_CAPACITY = 20; private int curCapacity; private int maxCapacity; private LinkedList<Cake> list; public Store() { this(MAX_INIT_CAPACITY); } public Store(int maxCapacity) { this.maxCapacity = maxCapacity; list = new LinkedList<>(); } //入库 - 生产者线程不断的调用 public synchronized void push(Cake cake){ if(curCapacity >= maxCapacity){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } curCapacity++; list.add(cake); System.out.println("入库,当前容量为:" + curCapacity); notify(); } //出库 - 消费者线程不断的调用 public synchronized Cake pop(){ if(curCapacity <= 0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } curCapacity--; Cake cake = list.removeFirst(); System.out.println("出库,当前容量为:" + curCapacity + " -- " + cake); notify(); return cake; } } public class Producer extends Thread{ private Store store; public Producer(Store store) { this.store = store; } @Override public void run() { while(true){ Cake cake = new Cake("好利来", LocalDateTime.now().toString()); store.push(cake); } } } public class Consumer extends Thread{ private Store store; public Consumer(Store store) { this.store = store; } @Override public void run() { while(true)