java多线程---生产者消费者模式

我所理解的生产者消费者模式  : 生产者有物品的时候则等待,没有则生产,生产后,通知消费者,也就是使用notifyall唤醒线程

                                                           消费者有物品则消费,没有就等待,通着生产者生产,唤醒线程

package com.qf.demo;

public class Test3 {
	public static void main(String[] args) {
		SuperMarket superMarket = new SuperMarket();
		// 
		FactoryDemo factoryDemo = new FactoryDemo(superMarket);
		Customer customer = new Customer(superMarket);
		// 
		Thread thread = new Thread(factoryDemo, "工厂");
		Thread thread2 = new Thread(customer, "顾客");
		// 
		thread.start();
		thread2.start();
	}
}

class Bread{
	int id ;
	String brand;
	public Bread(int id, String brand) {
		super();
		this.id = id;
		this.brand = brand;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}

}

class  SuperMarket{
	Bread[] breads = new Bread[6];
	int index = -1;// 从-1 开始表示什么都没有
	
	public synchronized void addBread(Bread bread){
		if(index>=5){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		index++;
		// 给面包数组赋值
		breads[index] = bread;
		System.out.println(Thread.currentThread().getName()+"生产了"+bread.getId()+"品牌是"+bread.getBrand()+"下标为"+index);
		this.notifyAll();
	}
	
	public synchronized void saleBread(){
		if(index<=-1){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 需求是打印一下被卖的面包的信息  , 让下标--
		Bread bread = breads[index];
		System.out.println(Thread.currentThread().getName()+"卖了"+bread.getId()+"品牌是"+bread.getBrand()+"下标为"+index);
		// 下标--
		index--;
		this.notifyAll();
	}
}

class FactoryDemo implements Runnable{

	// 使用容器类作为属性
	SuperMarket market;
	
	
	
	public FactoryDemo(SuperMarket market) {
		super();
		this.market = market;
	}



	@Override
	public void run() {
		for (int i = 0; i < 80; i++) {
			Bread bread = new Bread(i, Thread.currentThread().getName());
			market.addBread(bread);
		}
	}
	
}

class Customer implements Runnable{

	SuperMarket market;
	
	public Customer(SuperMarket market) {
		super();
		this.market = market;
	}

	@Override
	public void run() {
		for (int i = 0; i < 80; i++) {
			market.saleBread();
		}
	}
	
}
















创建面包类,超市使用这些面包,超市最多有6个,如果少于6个,则工厂类给予生产,消费者可以购买

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值