您的位置:首页 > 其它

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

2017-04-15 15:11 369 查看
class Producer implements Runnable {  

 *   private final BlockingQueue queue;  

 *   Producer(BlockingQueue q) { queue = q; }  

 *   public void run() {  

 *     try {  

 *       while(true) { queue.put(produce()); }  

 *     } catch (InterruptedException ex) { ... handle ...}  

 *   }  

 *   Object produce() { ... }  

 * }  

 *  

 * class Consumer implements Runnable {  

 *   private final BlockingQueue queue;  

 *   Consumer(BlockingQueue q) { queue = q; }  

 *   public void run() {  

 *     try {  

 *       while(true) { consume(queue.take()); }  

 *     } catch (InterruptedException ex) { ... handle ...}  

 *   }  

 *   void consume(Object x) { ... }  

 * }  

 *  

 * class Setup {  

 *   void main() {  

 *     BlockingQueue q = new SomeQueueImplementation();  

 *     Producer p = new Producer(q);  

 *     Consumer c1 = new Consumer(q);  

 *     Consumer c2 = new Consumer(q);  

 *     new Thread(p).start();  

 *     new Thread(c1).start();  

 *     new Thread(c2).start();  

 *   }  

 * }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: