package thread.producerconsumer;
public class StoreHouse {
private int base = 0;
private int top = 0;
private Product[] products = new Product[10];
public synchronized void push(Product product) {
while (top == products.length) {
notify();
try {
System.out.println("仓库已满,zwp正等待wxf消费...");
wait();
} catch (InterruptedException e) {
System.out.println("stop push product because other reasons");
// 必须用while,因为当线程在wait的时候被打断,那么程序会跳出if而去执行下一条语句
}
}
products[top] = product;
top++;
}
public synchronized Product pop() {
Product pro = null;
while (top == base) {
notify();
try {
System.out.println("仓库已空,wxf正等待zwp生产...");
wait();
} catch (InterruptedException e) {
System.out.println("stop push product because other reasons");
// 必须用while,因为当线程在wait的时候被打断,那么程序会跳出if而去执行下一条语句
}
}
top--;
pro = products[top];
products[top] = null;
return pro;
}
}
评论0