public class testProducerConsumer {
public static void main(String[] args) {
ProductContainer pc = new ProductContainer();
Producter producter = new Producter(pc);
Consumer consumer = new Consumer(pc);
new Thread(producter).start();
new Thread(consumer).start();
}
}
class Product {
private int ID;
Product(int ID) {
this.ID = ID;
}
public String toString() {
return "Product:" + ID;
}
}
class ProductContainer {
int index = 0;
Product[] product = new Product[10];
public synchronized void push(Product pro) {
while (index == product.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
product[index] = pro;
index++;
}
public synchronized Product pop() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return product[index];
}
}
class Producter implements Runnable {
ProductContainer pc = null;
Producter(ProductContainer pc) {
this.pc = pc;
}
public void run() {
for (int i = 0; i < 50; i++) {
Product p = new Product(i);
pc.push(p);
System.out.println("生产了:" + p);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
ProductContainer pc = null;
Consumer(ProductContainer pc) {
this.pc = pc;
}
public void run() {
for (int i = 0; i < 50; i++) {
Product pro = pc.pop();
System.out.println("消费了:" + pro);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}