用消息队列模拟生产者消费者模型

package blockqueen;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class xiaofeizhe {
 
  final BlockingQueue<String> queue=new ArrayBlockingQueue<String>(5);
 
 
 
 public static void main(String[] args) {
 
     xiaofeizhe xiaofeizhe=new xiaofeizhe();
     xiaofeizhe.begin();
 
}
 
 public  void begin() {
  
  Thread t1=new Thread(new chihuo());
  t1.start();
  
  Thread t2=new Thread(new laoban());
  t2.start();
  
 }
 
 class laoban  implements Runnable{
  
  int count=0;

  @Override
  public void run() {
   
       while(true)
       {
        
         try {
      Thread.sleep((long)(Math.random()*1000));
      queue.put("馒头"+(++count));
      System.out.println("生产一个馒头,总共生产了"+count+"个馒头"+"还有"+queue.size()+"个");
      
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
        
       }
   
  }
  
 }
 
 
 
 class chihuo  implements Runnable{
  
  int count=0;

  @Override
  public void run() {
   
       while(true)
       {
        
        
        try {
      Thread.sleep((long)(Math.random()*1000));
      
      System.out.println("吃一个馒头,总共吃了"+(++count)+"个馒头"+"还有"+queue.size()+"个"+"这是第"+queue.take()+"个馒头");
      
      
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
        
        
       }
   
  }
  
 }
 
 

 
 
 
}



你可能感兴趣的:(用消息队列模拟生产者消费者模型)