2008-08-23 19 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からその要素を削除するか、または を削除します。

関連する問題