手写消费者生产者模式

手写消费者生产者模式

public class Storage {
	 private static int MAX_VALUE = 100;
	 private List<Object> list = new ArrayList<>();
	 public void produce(int num) {
		 synchronized (list) {
			 while (list.size() + num > MAX_VALUE) {
				 System.out.println("暂时不能执行生产任务");
				 try {
				 	list.wait();
				 } catch (InterruptedException e) {
				 	e.printStackTrace();
				 }
			 }
			 for (int i = 0; i < num; i++) {
			 	list.add(new Object());
			 }
			 System.out.println("已生产产品数"+num+" 仓库容量"+list.size());
			 list.notifyAll();
		 }
	 }
	 public void consume(int num) {
	 	synchronized (list) {
			 while (list.size() < num) {
			 	System.out.println("暂时不能执行消费任务");
				 try {
				 	list.wait();
				 } catch (InterruptedException e) {
				 	e.printStackTrace();
				 }
			 }
			 for (int i = 0; i < num; i++) {
			 	list.remove(0);
			 }
			 System.out.println("已消费产品数"+num+" 仓库容量" + list.size());
			 list.notifyAll();
		 }
	 }
}
public class Producer extends Thread {
	 private int num;
	 private Storage storage;
	 public Producer(Storage storage) {
	 	this.storage = storage;
	 }
	 public void setNum(int num) {
	 	this.num = num;
	 }
	 public void run() {
	 	storage.produce(this.num);
	 }
}
public class Customer extends Thread {
	 private int num;
	 private Storage storage;
	 public Customer(Storage storage) {
	 	this.storage = storage;
	 }
	 public void setNum(int num) {
	 	this.num = num;
	 }
	 public void run() {
	 	storage.consume(this.num);
	 }
}
public class Test {
	 public static void main(String[] args) {
		 Storage storage = new Storage();
		 Producer p1 = new Producer(storage);
		 Producer p2 = new Producer(storage);
		 Producer p3 = new Producer(storage);
		 Producer p4 = new Producer(storage);
		 Customer c1 = new Customer(storage);
		 Customer c2 = new Customer(storage);
		 Customer c3 = new Customer(storage);
		 p1.setNum(10);
		 p2.setNum(20);
		 p3.setNum(80);
		 c1.setNum(50);
		 c2.setNum(20);
		 c3.setNum(20);
		 c1.start();
		 c2.start();
		 c3.start();
		 p1.start();
		 p2.start();
		 p3.start();
	 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值