java生产消费者模式

package productiveConsumption2;


/*
 * 面包类
 */
public class Bread {
private int id;
private String name;


public Bread(int id, String name) {
super();
this.id = id;
this.name = name;
}


public Bread() {
super();
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


@Override
public String toString() {
return "Bread [id=" + id + ", name=" + name + "]";
}


}


package productiveConsumption2;

//超市类
public class SuperMarket {
// 存面包的数量
Bread[] breads = new Bread[10];
// 记录下标
int index = -1;


// 进面包
public synchronized void getBread(Bread bread) {
if (index >= breads.length - 1) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
index++;
breads[index] = bread;
System.out.println("进面包:" + bread);
this.notify();
}


// 卖面包
public synchronized void saleBread() {
if (index < 0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("卖面包:" + breads[index]);
index--;
this.notify();
}
}

package productiveConsumption2;


/*
 * 消费者
 */
public class Coustomer implements Runnable {
private SuperMarket market;


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


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


}


}

package productiveConsumption2;
/*
 * 工厂类
 */
public class Factory implements Runnable{
private SuperMarket market;

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


@Override
public void run() {
for (int i = 1; i <= 20; i++) {
market.getBread(new Bread(i, "好吃面包" + i));
}

}


}

package productiveConsumption2;
/*
 * 测试类
 */
public class Test {


public static void main(String[] args) {
SuperMarket m = new SuperMarket();
Coustomer c = new Coustomer(m);
Factory f = new Factory(m);
Thread t1 = new Thread(c);
Thread t2 = new Thread(f);
t1.start();
t2.start();


}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值