浏览 1962 次
锁定老帖子 主题:生产者-使用者例子
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-03-10
最后修改:2011-03-10
好久不写东西了,写点小东西吧,呵呵 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(); } }
class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while(生产条件) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; private Thread p; Consumer(BlockingQueue q,Thread producer) { queue = q; p = producer;} public void run() { try { while(!p.isAlive()||!queue.isEmpty()) {//循环直到生产者线程结束并且把queue中的数据全部获取完 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(); } } public class Test { private ExecutorService producerPool = Executors.newFixedThreadPool(5); private ExecutorService consumerPool = Executors.newFixedThreadPool(5); private BlockingQueue queue = new ArrayBlockingQueue(100); public void t() { for (int i = 0; i 0) { String s = null; try { s = queue.take(); System.out.println("get a product:"+s); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("consumer-" + Thread.currentThread().getName() + " is done!"); } }; consumerPool.submit(consumer); } consumerPool.shutdown(); } public static void main(String[] args){ new Test().t(); } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |