2015-05-29 26 views
0

我有以下這段代碼對我來說很奇怪。日誌消息顯示當前線程未中斷,爲什麼?什麼時候線程的中斷標誌被設置?

final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10); 
Thread thread = new Thread() { 
    public void run() { 

    while (!Thread.currentThread().isInterrupted()) { 
     try { 
     LOG.info("start to take"); 
     String next = queue.take(); 
     LOG.info(next); 
     } catch (InterruptedException e) { 
     LOG.info(e + ""); 
     LOG.info("IsInterupted:" 
      + Thread.currentThread().isInterrupted()); 
     continue; 
     } 

    } 
    } 
}; 

thread.start(); 
Thread.sleep(1000); 
thread.interrupt(); 

回答

4

當某人在線程中調用.interrupt()時,它被設置。

你沒有在你的案例中看到中斷狀態的原因是.take()會在拋出異常時清除該標誌。

試試這個,看看:

Thread t = new Thread(() -> { 
    while (true) 
     System.out.println(Thread.currentThread().isInterrupted()); 
}); 
t.start(); 
Thread.sleep(1000); 
t.interrupt(); 

一般來說,.interrupt()以任何方式不被強迫(除非線程正在等待,看看下面的Javadoc獲取詳細信息) - 它是由該線程來輪詢它並採取相應的行動。 (如在此情況下,清除該標誌,並拋出一個InterruptedException。)

你可以閱讀更多的.interrupt()是如何在這裏工作:https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--

相關問題