public class producerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
Stock stock = new Stock();// TODO Auto-generated method stub
Producer producer = new Producer(stock);
Consumer consumer = new Consumer(stock);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class Bread {//产品类;
int id;
Bread(int id){
this.id = id;
}
public String toString(){
return "面包:"+id;
}
}
class Stock {//食品框类,堆栈实现;
private int index = 0;
private Bread[] bread= new Bread[5];//Bread已经在此处NEw出,main方法中不必再
public synchronized void push(Bread bread1){
if(index == bread.length){
System.out.println("容量已满");
System.out.println(index);
try {
this.wait();//停止生产;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();//面包框有空位时叫醒生产者‘
bread[index] = bread1;
++index;
}
public synchronized Bread pop(){
if(index== 0){
System.out.println("面包已售完");
try {
this.wait();//暂时停止消费;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify(); //继续消费;
--index;
return bread[index];
}
}
class Producer implements Runnable {//生产者类
Stock stock = null;
Producer(Stock stock){
this.stock = stock;
}
@Override
public void run() {
for(int i = 0;i<20;++i){
Bread bread = new Bread(i);// TODO Auto-generated method stub
stock.push(bread);
System.out.println("生产了"+bread);
try {
Thread.sleep(2000);
}catch(InterruptedException e){}
}
}
}
class Consumer implements Runnable {//消费者类
Stock stock = null;
Consumer(Stock stock){
this.stock = stock;
}
@Override
public void run() {
for(int i = 0;i<20;++i){
Bread bread = stock.pop();// TODO Auto-generated method stub
System.out.println("消费了"+bread);
try {
Thread.sleep(5000);
}catch(InterruptedException e){}
}
}
}