在没有遇到竞争条件的情况下,在并发程序中从BlockingQueue中获取对象的最佳方法是什么?我目前正在做以下事情,我不相信这是最好的方法:
BlockingQueuevQueue; /* 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 }
我还没有达到竞争状态......但是,我不确定这是否真的安全.
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文档BlockingQueue
.所以你可以看到你正在以正确的方式做到这一点.这是引用它告诉你它必须工作的引用:
内存一致性效果:与其他并发集合一样,在将对象放入BlockingQueue之前,线程中的操作发生在从另一个线程中的BlockingQueue访问或删除该元素之后的操作之前.