为什么线程Consume 必须用构造啊?我把它改成new的形式就好使,谁能给我解释一下,谢谢!
public class PC {
public static void main(String[] args) {
Factory f = new Factory();
Producer p = new Producer(f);
Consume c = new Consume();
new Thread(p).start();
new Thread(c).start();
}
}
//商品,货物
class Goods {
int id;
public Goods(int id) {
this.id = id;
}
// 重写toString方法
public String toString() {
return "Goods : " + id;
}
}
class Factory {
// 记录物品个数
int index = 0;
Goods[] goods = new Goods[10];
// 制造方法,每次调用,增加一个商品
public synchronized void produce(Goods g) {
//当容器已经满了,等待别人消费,wait,调用notify();等待别人消费后叫我再生产
while(index == goods.length){
try {
this.wait();//Object类的wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
goods[index] = g;
index++;
}
// 消费方法
public Goods consume() {
synchronized (this) {
//当容器没有商品了,等待生产者生产,自己wait,调用notify();等待别人生产后叫我去消费
while(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return goods[index];
}
}
}
class Producer implements Runnable {
Factory f = null;
public Producer(Factory f) {
this.f = f;
}
public void run() {
for (int i = 0; i < 50; i++) {
Goods g = new Goods(i);
f.produce(g);
System.out.println("生产了:" + g);
try {//生产一个睡一会儿
Thread.sleep((int) (Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consume implements Runnable {
Factory f = null;
// public Consume(Factory f){
// this.f = f;
// }
public void run() {
for (int i = 0; i < 50; i++) {
Goods g = new Goods(i);
f = new Factory();
f.consume();
System.out.println("我消费了:" + g);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}