黑马程序员_生产者和消费者问题

------- <a href=" http://www.itheima.com " target="blank">android培训</a>、<a href=" http://www.itheima.com " target="blank">java培训</a>、期待与您交流! ----------
 对于多个生产者和消费者,必须生产者产生商品后消费者才能消费
考虑:
1:生产者生产商品后通知消费者消费
2:消费者消费 后通知生产商品
3:商品增加和减少时必须同步
定义商品类
class Resource {
private String name;
private int count = 1;
private boolean flag = false;

// 商品增加
public synchronized void setAdd(String name) {
while (flag) {//有商品等待
try {
this.wait();
} catch (Exception e) {
System.out.println("出错了" + e);
}
}
this.name = name + "编号为" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者产生..."
+ this.name);
flag = true;//生产商品后将商品标志设为真
this.notifyAll();
}

public synchronized void out() {
while (!flag) {//无商品等待
try {
wait();
} catch (Exception e) {
System.out.println("出错了" + e);
}
}
System.out.println(Thread.currentThread().getName() + "...消费者消费..."
+ this.name);
flag = false;//消费后商品标志设为假
this.notifyAll();
}
}

定义生产者类
class Producer implements Runnable {
private Resource res;

Producer(Resource res) {
this.res = res;
}

public void run() {
while (true) {
res.setAdd("商品一");
}
}
}

定义消费者类
class Consumer implements Runnable {
private Resource res;

Consumer(Resource res) {
this.res = res;
}

public void run() {
while (true) {
res.out();
}
}
}

主函数中生成多个线程序
public static void main(String[] args) throws InterruptedException {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
Thread.sleep(100);
System.exit(0);
}  
思考
 
 对于多个生产者和消费者。
 为什么要定义while判断标记。
 原因:让被唤醒的线程再一次判断标记。
 为什么定义notifyAll,
 因为需要唤醒对方线程。
 因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。
为什么商品增加和减少的方法定义在商品中,而不在生产者和消费者中呢?
原因:商品的增加和减少是商品的变量,所以方法应该在商品中(变量数据在那个类中,方法 也就在那个类中)别人要的是调用方法。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值