首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

生产者-使用者例证

2012-12-21 
生产者-使用者例子好久不写东西了,写点小东西吧,呵呵 这是一个简单的生产者-消费者例子(取自java 6.0 api

生产者-使用者例子

好久不写东西了,写点小东西吧,呵呵

这是一个简单的生产者-消费者例子(取自java 6.0 api介绍java.util.concurrent 接口 BlockingQueue时举的例子)

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();    } } 

?


这个例子非常易于理解,特征明显,属于典型案例,但我们平时的应用一般不会无限循环下去,我们需要消费者在生产者结束后把queue中的数据获取出来、做完相应的操作以后结束生产消费过程。 针对该需求可以修改一下程序,做一个单生产者的例子,如下:

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(); } } 

?

热点排行