2008-08-23 49 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中刪除該元素。

相關問題