java 多线程 生产者消费者问题

**问题:**生产者生产面包,当面包的数量大于6时,生产者就不能再生产了。当面包数量小于等于0时,消费者也不能再继续消费。
**思路:**第一步,我们创建一个面包类Bread,定义面包的属性。第二步,创建一个容器类,用来存放面包以及定义两种操作,存放面包和取出面包。第三步,创建消费者类和生产者类,实现Runnable接口,并重写run方法。最后,创建一个Test类进行测试。
源代码:

//面包类
public class Bread {
	private int Id;
	private String productName;
	public Bread() {
		// TODO Auto-generated constructor stub
	}
	public Bread(int id, String productName) {
		super();
		Id = id;
		this.productName = productName;
	}
	public int getId() {
		return Id;
	}
	public void setId(int id) {
		Id = id;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	@Override
	public String toString() {
		return "Bread [Id=" + Id + ", productName=" + productName + "]";
	}
	
	
}
public class BreadCon {
	//存放面包的数组
	private Bread[] cons = new Bread[6];
	//存放面包的位置
	private int index = 0;
	
	//存放面包
	public synchronized void input(Bread b){  //锁this
		//判断容器有没有满
		while(index>=6){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		cons[index] = b;
		System.out.println(Thread.currentThread().getName()+"生产了"+b.getId()+"生产者"+b.getProductName());
		index++;
		//唤醒
		this.notifyAll();
	
	}
	//取出面包
	public synchronized void output(){  //锁this
		while(index<=0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		index--;
		Bread b = cons[index];
		
		
		System.out.println(Thread.currentThread().getName()+"消费了"+b.getId()+"生产者"+b.getProductName());
		
		//唤醒
		this.notifyAll();
		
		
	
	}
}
public class Consume implements Runnable{
	
	private BreadCon con;
	
	public Consume(BreadCon con) {
		super();
		this.con = con;
	}
	@Override
	public void run() {
		for(int i=0;i<30;i++){
			con.output();
		}
		
	}
	
	
}
public class Prodcut implements Runnable{
	private BreadCon con;

	public Prodcut(BreadCon con) {
		super();
		this.con = con;
	}

	@Override
	public void run() {
		for(int i=0;i<30;i++){
			con.input(new Bread(i, Thread.currentThread().getName()));
		}
		
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿研究僧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值