2008-08-23 24 views
4

在并发程序中将对象从BlockingQueue中取出而不碰到竞争条件的最佳方法是什么?我目前在做以下,我不相信这是最好的方法:从并发程序中的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 
} 

我还没有打一场比赛的条件...但是,我一点也不知道这是真正安全。

回答

6
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中删除该元素。

相关问题