老师,在生产者消费者模式里面,wait和notify是不是都要在Good里面呢,我写在Producer和Consumer里好像就不起作用了,为什么?代码如下:
package com.produceandcomsume;
public class Goods {
boolean isEmpty;
private String name;
private String brand;
public Goods(String name, String brand) {
super();
this.name = name;
this.brand = brand;
}
public Goods() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
package com.produceandcomsume;
class Producer implements Runnable {
Goods good;
public Producer(Goods good) {
this.good = good;
}
@Override
public void run() {
producer();
}
public synchronized void producer() {
if(!good.isEmpty) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
good.setBrand("娃哈哈");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
good.setName("矿泉水");
System.out.println(Thread.currentThread().getName() + "生产了-->" + good.getBrand() + good.getName());
} else {
good.setBrand("旺仔");
good.setName("小馒头");
System.out.println(Thread.currentThread().getName() + "生产了-->" + good.getBrand() + good.getName());
}
super.notifyAll();
good.isEmpty = false;
}
}
}
package com.produceandcomsume;
public class Consumer implements Runnable {
Goods good;
public Consumer(Goods good) {
this.good = good;
}
@Override
public void run() {
consume();
}
public synchronized void consume() {
if(good.isEmpty) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
good.getBrand();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
good.getName();
System.out.println(Thread.currentThread().getName() + "消费了-->" + good.getBrand() + good.getName());
}
super.notifyAll();
good.isEmpty = true;
}
}
package com.produceandcomsume;
public class Demo {
public static void main(String[] args) {
Goods goods = new Goods();
goods.isEmpty = true;
Thread producer = new Thread(new Producer(goods), "生产者");
Thread consumer = new Thread(new Consumer(goods), "消费者");
producer.start();
consumer.start();
}
}
运行结果:
