setName(String name) {
this.name = name;
}
}
class Storage {
private Product[] products = new Product[10];
private int top = 0;
public synchronized void push(Product product) {
while (top == products.length) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
products[top++] = product;
System.out.println(Thread.currentThread().getName() + \" 生产了产品\"
+ product);
notifyAll();
}
public synchronized Product pop() {
while (top == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
--top;
Product p = new Product(products[top].getId(), products[top].getName());
products[top] = null;
System.out.println(Thread.currentThread().getName() + \" 消费了产品\" + p);
notifyAll();
return p;
}
}
</span>
运行结果:
生产者 生产了产品(产品ID:010435111 产品名称:电话)
消费者 消费了产品(产品ID:010435111 产品名称:电话)