2015-01-16 4 views
1

다음 방법이 맞는지 알고 싶습니다. 공통의 BlockingQueue에서 작동하는 제작자 및 소비자 스레드가 있습니다. 제작자가 스니퍼 스레드이므로 자동으로 중지되지만 소비자가 생산자 스레드의 상태 (활성/비활성)에 대한 루프로 종료하는 것으로 생각됩니다. 어떤 제안? 감사합니다스레드 소비 큐, 종료

-) 메인 스레드에서 :

ArrayBlockingQueue<PcapPacket> queue = new ArrayBlockingQueue<>(); 
    Producer p = new Producer(queue); 
    Thread t1 =new Thread(p); 
    t1.start(); 
    Consumer c = new Consumer(queue,t1); 
    new Thread(c).start(); 

-) 프로듀서

public void run() { 
     public void nextPacket(PcapPacket packet, String user) { 
      try { 
       queue.put(packet); 
      } catch (InterruptedException ex) { 

      } 

-) 소비자

public void run() { 
    while(producer.isAlive()){ 
     try { 
     //Thread.sleep(50); 
     packet=queue.take(); 

답변

0

폴링 프로듀서의 상태는 하위 최적입니다.

class Producer implements Runnable { 

    static final Object TIME_TO_STOP = new Object(); 

    private final BlockingQueue<Object> q; 

    Producer(BlockingQueue<Object> q) { 
     this.q = q; 
    } 


    @Override 
    public void run() { 
     try { 
      while (true) { 
       q.put(readNextPacket()); 
      } 
     } finally { 
      // exception happened 
      try { 
       q.put(TIME_TO_STOP); 
      } catch (InterruptedException e) { 
       // somehow log failure to stop properly 
      } 
     } 
    } 
} 

class Consumer implements Runnable { 

    private final BlockingQueue<Object> q; 

    Consumer(BlockingQueue<Object> q) { 
     this.q = q; 
    } 

    @Override 
    public void run() { 
     while (true) { 
      Object packet = q.take(); 
      if (packet == Producer.TIME_TO_STOP) { 
       break; 
      } 
      // process packet 
     } 
    } 
} 
:

선호하는 접근 방식은 생산 종료하는 동안, 생산을 큐에 약간의 '극약 처방'을 놓고, 소비자는 즉시 그 약을받은 것처럼 루프의 끝을 위해하는 것입니다