2013-03-18 28 views
2

我有非常簡單的代碼,它使用「毒丸」模擬生產者/消費者停止技術。使用毒藥丸不能阻止生產者/消費者線程

我有監製類:

public class Producer extends Thread { 

    private final BlockingQueue<String> queue; 

    public Producer(BlockingQueue<String> queue) { 
     this.queue = queue; 
    } 

    @Override 
    public void run() { 
     try { 
     while (true) { 
       //unblocking this line will cause the code to stop after intrrupt    
       //System.out.println("1"); 
       queue.put("hello world"); 
      } 
     } catch (InterruptedException e) { 
       try { 
        queue.put(Main.POISON_PILL); 
       } catch (InterruptedException e1) { 
       } 
      } 
     } 
} 

消費階層:

public class Consumer extends Thread { 

    private final BlockingQueue<String> queue; 

    public Consumer(BlockingQueue<String> queue) { 
     this.queue = queue; 
    } 

    @Override 
    public void run() { 
     try { 
      while (true) { 
       String s = queue.take(); 
       if (s.equals(Main.POISON_PILL)) 
        break; 
       else 
        System.out.println(s); 
      } 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
     } 
    } 
} 

現在的主要功能:

public static String POISON_PILL = "POISON_PILL"; 

    public static void main(String[] args) { 

     BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); 
     Producer producer = new Producer(queue); 
     Consumer consumer = new Consumer(queue); 
     producer.start(); 
     consumer.start(); 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 

     } finally { 
      producer.interrupt(); 
     } 
    } 

因爲即使producer.interrupt()稱爲後不知道原因, 「你好世界「永遠在控制檯上進行打印。

我無法理解的第二件事是爲什麼取消註釋System.out.println("1");將導致程序在生產者線程中斷後退出。

請幫我理解爲什麼。

回答

4

我的猜測是,你的製片人跑得比你的消費者快得多,你出現永遠不會用完的項目。在沒有明確容量的情況下創建LinkedBlockingQueue會創建一個容量爲Integer.MAX_VALUE的容器,該容量足以讓消費者在相當長一段時間內保持打印。

這也可能是它添加System.out.println行時開始工作的原因;通過要求控制檯I/O,它會減慢生產者到消費者能夠跟上的程度。

嘗試創建一個LinkedBlockingQueue與一些小容量,如100左右,而不是。

+0

您也可以在發佈藥丸之前排空隊列。 – OldCurmudgeon 2013-03-19 00:11:06

+0

你是對的。 – 2013-03-19 00:13:58