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/alamps/p/2736351.html