/*
通过wait notifyAll机制来实现 线程的同步,消费者消费必须在生产者生产之后才能进行
*/
public static void main(String[] args)
{
Storage storage = new Storage();
Thread consumer = new Thread(new Consumer(storage));
consumer.setName("消费者");
Thread producer = new Thread(new Producer(storage));
producer.setName("生产者");
consumer.start();
producer.start();
}
}
class Consumer implements Runnable{
private Storage storage;
public Consumer(Storage storage){
this.storage = storage;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Consumer run");
storage.pop();
}
}
class Producer implements Runnable{
private Storage storage;
public Producer(Storage storage){
this.storage = storage;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Producer run");
Product product = new Product("090505105", "电话");
storage.push(product);
}
}
class Product{
private String id;
private String name;
public Product(String id,String name){
this.id = id;
this.name = name;
}
@Override
public String toString()
{
return "(产品ID:\" + id + \" 产品名称:\" + name + \")";
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
class Storage{
private Product[] products = new Product[10];
private int top = 0;
public synchronized void push(Product product){
System.out.println("Producer push");
while(top == products.length)
{
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
products[top++] = product;
System.out.println(Thread.currentThread().getName() + " 生产了产品"
+ product);
System.out.println("Producer notifyAll after push");
notifyAll();//唤醒等待线程
}
public synchronized Product pop(){
System.out.println("Producer pop");
while(0 == top){
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);
System.out.println("Producer notifyAll after pop");
notifyAll();//唤醒等待线程
return p;
}
}