2008-08-23 10 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에서 해당 요소를 액세스하거나 제거하십시오.

관련 문제