【问题标题】:Best method to get objects from a BlockingQueue in a concurrent program?在并发程序中从 BlockingQueue 获取对象的最佳方法?
【发布时间】:2008-08-23 04:03:18
【问题描述】:

在并发程序中从 BlockingQueue 中取出对象而不遇到竞争条件的最佳方法是什么?我目前正在执行以下操作,但我不相信这是最好的方法:

BlockingQueue<Violation> vQueue;
/* 
in the constructor I pass in a BlockingQueue object 
full of violations that need to be processed - cut out for brevity
*/

Violation v;
while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) ) != null ) {
    // do stuff with the violation
}

我还没有达到比赛条件...但是,我不太确定这是否真的安全。

【问题讨论】:

    标签: java concurrency


    【解决方案1】:
    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();
       }
     }
    

    这个例子取自JDK 1.6 docs of BlockingQueue。因此,您可以看到您正在以正确的方式进行操作。这是告诉您它必须起作用的报价:

    内存一致性效果:与 其他并发集合、动作 在放置对象之前在线程中 进入 BlockingQueue 发生之前 访问后的操作或 从 BlockingQueue 在另一个线程中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      相关资源
      最近更新 更多