仓储模型,线程池

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值