学习记录327@Java仓储模型

it2023-07-20  68

本质上仓储模型也是生产者消费者模型,只是多了一个仓库,仓库中添加和取出生产者和消费者共享的产品变量

//产品 package com.dream.test05; public class Cake { private String brand; private String date; public Cake() { super(); } public Cake(String brand, String date) { super(); this.brand = brand; this.date = date; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Override public String toString() { return "Cake [brand=" + brand + ", date=" + date + "]"; } } //仓库 package com.dream.test05; import java.util.LinkedList; public class Store { private LinkedList<Cake> list = new LinkedList<>(); private int max=20; private int count; //添加商品 public void push(Cake cake) { synchronized (this) { while (count >= max) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } list.add(cake); System.out.println("入库," + "此时仓库库存为:" + (++count)); this.notifyAll(); } } //取出商品 public void pop() { synchronized (this) { while (count <= 0) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Cake first = list.removeFirst(); System.out.println("出库:" + first + "剩余库存为:" + (--count)); this.notifyAll(); } } } //生产者 package com.dream.test05; import java.text.SimpleDateFormat; import java.util.Date; public class Producer extends Thread { private Store store; public Producer() { super(); } public Producer(Store store) { super(); this.store = store; } @Override public void run() { // TODO Auto-generated method stub while (true) { Cake cake = new Cake("好利来", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } store.push(cake); } } } //消费者 package com.dream.test05; public class Consumer extends Thread { private Store store; public Consumer() { super(); } public Consumer(Store store) { super(); this.store = store; } @Override public void run() { while (true) { // TODO Auto-generated method stub try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } store.pop(); } } } //测试 package com.dream.test05; public class Test01 { public static void main(String[] args) { Store store = new Store(); Producer producer1 = new Producer(store); Consumer consumer1 = new Consumer(store); Producer producer2 = new Producer(store); Consumer consumer2 = new Consumer(store); producer1.start(); consumer1.start(); producer2.start(); consumer2.start(); } }

最新回复(0)