------- <a href="
http://www.itheima.com
" target="blank">android培训</a>、<a href="
http://www.itheima.com
" target="blank">java培训</a>、期待与您交流! ----------
对于多个生产者和消费者,必须生产者产生商品后消费者才能消费
考虑:
1:生产者生产商品后通知消费者消费
2:消费者消费 后通知生产商品
3:商品增加和减少时必须同步
定义商品类
对于多个生产者和消费者,必须生产者产生商品后消费者才能消费
考虑:
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,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。
为什么商品增加和减少的方法定义在商品中,而不在生产者和消费者中呢?
原因:商品的增加和减少是商品的变量,所以方法应该在商品中(变量数据在那个类中,方法 也就在那个类中)别人要的是调用方法。
为什么商品增加和减少的方法定义在商品中,而不在生产者和消费者中呢?
原因:商品的增加和减少是商品的变量,所以方法应该在商品中(变量数据在那个类中,方法 也就在那个类中)别人要的是调用方法。