|
3Java金币
import java.util.LinkedList;
public class ProducerConsumer01 {
public LinkedList<Object> storeHouse = new LinkedList<Object>();
public String name;// 产品名字
public int num = 0;// 编号
// 加工
class Producer implements Runnable {
public void run() {
while (true) {
print();
}
}
public synchronized void print() {
// this.notify();
if (storeHouse.size() == 5) {// 生产了5个后就等待
// this.notify();
try {
// this.wait();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
name = "蛋糕" + num;
storeHouse.offerLast(name);// 每生产一个就把它放在最后
System.out.println(Thread.currentThread().getName() + "生产了" + name);
// if (storeHouse.size() == 5) {// 生成了5个后就唤醒
// notify();
this.notify();
// }
}
}
// 消费类
class Consumer implements Runnable {
public void run() {
while (true) {
print1();
}
}
public synchronized void print1() {
// this.notify();
if (storeHouse.size() == 0) {// 卖完了之后就等待
this.notify();
try {
wait();
// this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "卖出去了:"
+ storeHouse.pollFirst());
// if (storeHouse.size() == 0) {
// notify();
this.notify();
// }
}
}
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
ProducerConsumer.Consumer cs = pc.new Consumer();
ProducerConsumer.Producer pd = pc.new Producer();
Thread td1 = new Thread(cs, "商店");
Thread td2 = new Thread(pd, "工厂");
td1.start();
td2.start();
}
}
这段代码希望能够重复交替的输出五个,为什么输出五个后就死掉了?
|
|