**问题:**生产者生产面包,当面包的数量大于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()));
}
}
}