生产者与消费者 java经典线程法

   

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){}
  }
   
  
 }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值