面包消费

package test08;

public class BreadAA {
public static void main(String[] args) {
//1创建容器
BreadCon con=new BreadCon();
//2生产
Product product=new Product(con);
//3消费
Consume consume=new Consume(con);
//4线程对象
Thread shaqiang=new Thread(product, “莎强”);
Thread xiaocang=new Thread(consume,”小苍”);
//5启动
shaqiang.start();
xiaocang.start();
}
}
class Bread {
private int id;
private String productName;
public Bread() {
// TODO Auto-generated constructor stub
}

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 + "]";
}

}

class Consume implements Runnable{
private BreadCon con;
public Consume(BreadCon con) {
this.con=con;
}
@Override
public void run() {
for(int i=1;i<=100;i++){
con.output();
}
}
}
/*
* 生产面包类
*/
class Product implements Runnable{
private BreadCon con;
public Product(BreadCon con) {
this.con=con;
}
@Override
public void run() {
for(int i=1;i<=100;i++){
Bread b=new Bread(i, Thread.currentThread().getName());
this.con.input(b);
}
}
}/*
* 面包容器
*/
class BreadCon
{
private Bread con;
private boolean flag; //

//放入面包
public synchronized void input(Bread b){
    while(flag==true){
        try {
            this.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    this.con=b;
    System.out.println(Thread.currentThread().getName()+"生产了"+b.getId());
    flag=true;
    this.notifyAll();
}

// 消费的面包
public synchronized void output(){
while(flag==false){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bread b=con;
con=null;// 减少内存浪费没其他作用
System.out.println(Thread.currentThread().getName()+”消费了”+b.getId()+” 生产者:”+b.getProductName());
flag=false;
this.notifyAll();
}
}

猜你喜欢

转载自blog.csdn.net/mingxu_W/article/details/81810697