生产者消费者问题

1.生产者消费者问题

 生产者消费者类

 

public class Producer {
	public void produce(){
		System.out.println("生产一个");
	}
}
public class Consumer {
	public void consumer(){
		System.out.println("消费一个");
	}
}

  

  超市实体类

  

public class SuperMark {

	// 此超市最大库存是3
	// 当超市库存为0时,消费者不能消费
	// 当超市库存==3时,生产者不能生产

	// 最大库存
	private final int MAX_STORE = 3;
	// 当前库存
	private int currentStore = 3;

	Producer producer;

	Consumer consumer;
        
        public SuperMark() {

		producer = new Producer();
		consumer = new Consumer();

	}

	public  synchronized void stockProduct() {

		while (MAX_STORE == currentStore) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		producer.produce();

		currentStore++;
		System.out.println("当前库存" + currentStore);
		notify();
	}
	
	
	public  synchronized void sellProduct(){
		while (0 == currentStore) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		consumer.consumer();
		currentStore--;
		System.out.println("当前库存"+currentStore);
		notify();
	}

 

  消费和生产线程类

  

class ProduceThread extends Thread{
	
	SuperMark superMark;
	
	public ProduceThread(SuperMark superMark){
		this.superMark=superMark;
	}
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			superMark.stockProduct();
		}
	}
}




class ConsumerThread extends Thread{
	
	SuperMark superMark;
	
	public ConsumerThread(SuperMark superMark){
		this.superMark=superMark;
	}
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			superMark.sellProduct();
		}
	}
	
}

 

  测试类

  

public static void main(String[] args) {
		SuperMark superMark = new SuperMark();
		ProduceThread thread1 = new ProduceThread(superMark);
		ConsumerThread thread2 = new ConsumerThread(superMark);
		ProduceThread thread3 = new ProduceThread(superMark);
		ConsumerThread thread4 = new ConsumerThread(superMark);
		thread1.start();
		thread3.start();
		thread4.start();
		thread2.start();
}

 

  结果

  

消费一个
当前库存2
消费一个
当前库存1
消费一个
当前库存0
生产一个
当前库存1
生产一个
当前库存2

 

  可以看出库存不会大于3和低于0

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值