多线程 生产者消费者模式 线程之间的通讯问题

来源:互联网 发布:暴力营销软件 编辑:程序博客网 时间:2024/06/04 19:58
  1. class Producer implements Runnable {  
  2.  *   private final BlockingQueue queue;  
  3.  *   Producer(BlockingQueue q) { queue = q; }  
  4.  *   public void run() {  
  5.  *     try {  
  6.  *       while(true) { queue.put(produce()); }  
  7.  *     } catch (InterruptedException ex) { ... handle ...}  
  8.  *   }  
  9.  *   Object produce() { ... }  
  10.  * }  
  11.  *  
  12.  * class Consumer implements Runnable {  
  13.  *   private final BlockingQueue queue;  
  14.  *   Consumer(BlockingQueue q) { queue = q; }  
  15.  *   public void run() {  
  16.  *     try {  
  17.  *       while(true) { consume(queue.take()); }  
  18.  *     } catch (InterruptedException ex) { ... handle ...}  
  19.  *   }  
  20.  *   void consume(Object x) { ... }  
  21.  * }  
  22.  *  
  23.  * class Setup {  
  24.  *   void main() {  
  25.  *     BlockingQueue q = new SomeQueueImplementation();  
  26.  *     Producer p = new Producer(q);  
  27.  *     Consumer c1 = new Consumer(q);  
  28.  *     Consumer c2 = new Consumer(q);  
  29.  *     new Thread(p).start();  
  30.  *     new Thread(c1).start();  
  31.  *     new Thread(c2).start();  
  32.  *   }  
  33.  * }  
0 0