在并发程序中,从 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
}
我还没有达到竞争条件......但是,我不太确定这是否真的安全。
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 http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html。所以你可以看到你正在以正确的方式做这件事。以下引用告诉您它必须起作用:
内存一致性影响:与
其他并发集合、操作
在放置对象之前在线程中
进入 BlockingQueue 之前发生的情况
访问后的操作或
从中删除该元素
另一个线程中的BlockingQueue。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)