面包类-生产的对象
public class Bread {
private int id;
private String productName;
public Bread() {
}
public Bread(int id, String productName) {
super();
this.id = id;
this.productName = productName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.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 + '\'' +
'}';
}
}
BreadCon.class-容器
public class BreadCon {
//存放面包的数组
private Bread[] cons=new Bread[6];
//存放面包的位置
private int index=0;
//存放面包
public synchronized void input(Bread b){
//判断有没有满
while (index>=6){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cons[index]=b;
System.out.println(Thread.currentThread().getName()+"生产了"+b.getId()+"");
index++;
//唤醒
this.notifyAll();
}
//取出面包
public synchronized void output(){
while (index<=0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
Bread b=cons[index];
System.out.println(Thread.currentThread().getName()+"消费了"+b.getId()+"生产者"+b.getProductName());
cons[index]=null;
//唤醒
this.notifyAll();
}
}
Proudct.class-生产者
public class Product implements Runnable {
private BreadCon con;
public Product(BreadCon con) {
this.con = con;
}
@Override
public void run() {
for (int i = 0; i <30 ; i++) {
con.input(new Bread(i,Thread.currentThread().getName()));
}
}
}
Consume.class-消费者
public class Consume implements Runnable{
private BreadCon con;
public Consume(BreadCon con) {
this.con = con;
}
@Override
public void run() {
for (int i = 0; i <30; i++) {
con.output();
}
}
}
TestBread.class-测试类
下面展示一些 内联代码片
。
public class TestBread {
public static void main(String[] args) {
//容器
BreadCon con=new BreadCon();
//生产和消费
Product product=new Product(con);
Consume consume=new Consume(con);
//创建消费对象
Thread chenchen=new Thread(product,"chenchen");
Thread mingming=new Thread(consume,"mingming");
Thread lili=new Thread(product,"lili");
Thread bingbing=new Thread(consume,"bingbing");
chenchen.start();
lili.start();
mingming.start();
bingbing.start();
}
}