2011-11-08 37 views
5

我想中斷一個線程,但調用中斷()似乎不工作,下面是示例代碼:爲什麼中斷()無法按預期工作,它是如何工作

public class BasicThreadrRunner { 
    public static void main(String[] args) { 
     Thread t1 = new Thread(new Basic(), "thread1"); 
     t1.start(); 
     Thread t3 = new Thread(new Basic(), "thread3"); 
     Thread t4 = new Thread(new Basic(), "thread4"); 
     t3.start(); 
     t1.interrupt(); 
     t4.start(); 
    } 
} 
class Basic implements Runnable{ 
    public void run(){ 
     while(true) { 
      System.out.println(Thread.currentThread().getName()); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       System.err.println("thread: " + Thread.currentThread().getName()); 
       //e.printStackTrace(); 
      } 
     } 
    } 
} 

,但輸出的樣子thead1仍在運行。所以,任何人都可以解釋它,()的作品,如何中斷感謝

回答

12

因爲你趕上InterruptedException線程仍在只需運行和保持運行。 interrupt()主要是設置一個標誌在Thread對象,你可以用isInterrupted()檢查。這也導致了一些方法 - sleep()joinObject.wait(),尤其是 - 通過拋出InterruptedException立即返回。它也會導致一些I/O操作立即終止。如果您發現您的catch塊打印出來,然後你可以看到,interrupt()工作。

+0

:感謝您的幫助 – jason

10

正如其他人所說,你趕上中斷,但確實與它無關。你需要做的是使用邏輯,例如,

while(!Thread.currentThread().isInterrupted()){ 
    try{ 
     // do stuff 
    }catch(InterruptedException e){ 
     Thread.currentThread().interrupt(); // propagate interrupt 
    } 
} 

使用循環邏輯,如while(true)只是懶惰的編碼傳播中斷。相反,輪詢線程的中斷標誌以確定通過中斷終止。

+0

或者您可以將try/catch移到循環之外。 ;) –

+2

是的,但那已經由@MByD提到的,是它讓壞的循環邏輯不變。 :D – mre

+0

@mre:謝謝你的親友 – jason

相關問題