Java线程:生产者消费者模型

public class ProduceConsume {

 /** 

  *@param 生产消费程序
  * @author wenhaibo
  */
 public static void main(String[] args) {
  Container container=new Container();
  Producer p=new Producer(container);
  Consumer c=new Consumer(container);
  new Thread(p).start();
  new Thread(c).start();
 }

}
class Food{
 //标记食物ID
 int id;
 Food(int id){
  this.id=id;
 }
 public String toString(){
  return "食物 id :"+id;
 }
}
class Container{
 //为容器定义下标值和容量
 int index=0;
 Food[] arryfood=new Food[10];
  //提供往容器仍食物的方法
 public synchronized void still(Food food){
  if(index==arryfood.length){
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  this.notify();
  arryfood[index]=food;
  index++;
 }
 //提供往容器拿食物的方法
 public synchronized Food hold(){
  if(index==0){
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  this.notify();
  index--;
  return arryfood[index];  
 }
}
class Producer implements Runnable{
 // 生产者生产食物
 Container container=null;
 public Producer(Container container) {
  //提供装食物的容器
  this.container=container;
 }
 public void run() {
 //开始生产食物放进容器里
  for(int i=0;i<20;i++){
   Food food=new Food(i);
   container.still(food);
   System.out.println("生产了 :"+food);
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
 }
 
}
class Consumer implements Runnable{
 //消费者消费食物
 Container container=null;
 Consumer(Container container){
  this.container=container;
 }
 public void run() {
  // 开始消费食物
  for(int i=0;i<20;i++){
   Food food=container.hold();
   System.out.println("消费了 :"+food);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
}

转载于:https://www.cnblogs.com/wenhaibo/archive/2010/07/31/1789250.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值