2013-03-10 46 views
2

我只是即興使用線程中斷取消線程。雖然在我的代碼中兩個線程都停止了,但看起來我並沒有趕上InterruptedException我只是想知道爲什麼?中斷正在運行的線程

監製:

public class Producer implements Runnable{ 

    private BlockingQueue<String> queue ; 

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

    @Override 
    public void run() { 
      try { 

     while (!Thread.currentThread().isInterrupted()){ 
       queue.put("Hello"); 
      } 
     }catch (InterruptedException e) { 
       System.out.println("Interupting Producer"); 
       Thread.currentThread().interrupt(); 
     } 
    } 
} 

消費者:

public class Consumer implements Runnable { 

    BlockingQueue<String> queue; 

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

    @Override 
    public void run() { 

     String s; 
     try { 
      while (!Thread.currentThread().isInterrupted()) { 
       s = queue.take(); 
       System.out.println(s); 
      } 
     } catch (InterruptedException e) { 
      System.out.println("Consumer Interupted"); 
      Thread.currentThread().interrupt(); 
     } 
    } 
} 

現在主營:

public static void main(String[] args) { 
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); 

    Thread producerThread = new Thread(new Producer(queue)); 
    Thread consumerThread = new Thread(new Consumer(queue)); 
    producerThread.start(); 
    consumerThread.start(); 

    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
    } finally { 
     producerThread.interrupt(); 
     consumerThread.interrupt(); 
    } 
} 

雖然線程停下來,我不明白爲什麼InterruptedException不咳嗽。 它應該打印catch塊內的中斷消息,但沒有打印

+2

這可能不應該有'Java的ee'標籤... – 2013-03-10 15:22:48

+0

如何您認爲?中斷的線程是否可以檢查狀態? – 2013-03-10 15:28:30

回答

3

你有一個無界的隊列,因此生產者和消費者都不會在隊列上被阻塞。因此,沒有可能拋出InterruptedException的操作被中斷。

1

這裏是連接例子中斷:

公共類TestThread1實現Runnable {

public void run() { 
    while(Thread.currentThread().isInterrupted() == false) { 
     System.out.println("dans la boucle"); 

     //on simule une courte pause 

     for(int k=0; k<100000000; k++); 

     System.out.println("Thread isInterrupted = " + Thread.currentThread().isInterrupted()); 
    } 
} 

public static void main(String[] args) { 
    Thread t = new Thread(new TestThread1()); 
    t.start(); 

    //on laisse le temps à l'autre Thread de se lancer 
    try { 
     Thread.sleep(1000); 

    } catch(InterruptedException e) {} 

    System.out.println("interruption du thread"); 
    t.interrupt(); 
} 

}

執行的結果是:

丹斯拉仿羔皮呢

線程isInterrupted =假

丹斯拉仿羔皮呢

中斷線程杜

線程isInterrupted =真