雖然線程方法裏面有個方法爲interrupt(),即線程中斷,可是並非調用了線程中斷,線程就真的中斷了,若是線程在sleep中,則會被異常捕獲,例子以下: java
public static void main(String[] args) throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { System.out.println(i); i++; if (Thread.currentThread().isInterrupted()) { System.out.println("中斷標識爲真,我將中斷等待"); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("我被中斷異常捕獲"); } } } }); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(20 * 1000); }
運行結果:ide
能夠看到,程序並無中斷成功,反而被異常捕獲,這時候,咱們能夠想到,在異常裏執行中斷,該線程纔會中斷下來:線程
public static void main(String[] args) throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { System.out.println(i); i++; if (Thread.currentThread().isInterrupted()) { System.out.println("中斷標識爲真,我將中斷等待"); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("我被中斷異常捕獲"); // 在異常裏面增長中斷方法 Thread.currentThread().interrupt(); } } } }); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(20 * 1000); }
運行結果:code
能夠看到這個時候才真正中斷下來。因此使用中斷的時候,不但主線程要執行中斷,並且在執行線程的重點異常處,也要增長中斷。另外,若是線程在執行循環,則必定要增長if (thread.isInterrupted()),不然線程就算在異常裏面又一次執行了中斷,循環仍是會繼續執行,以下圖:io
public static void main(String[] args) throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { System.out.println(i); i++; try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("我被中斷異常捕獲"); // 在異常裏面增長中斷方法 Thread.currentThread().interrupt(); } } } }); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(20 * 1000); }
運行結果:class
所以若是有循環要記得判斷一下中斷標識。中斷標識一種是直接調用isInterrupted()方法判斷,另外還能夠經過在線程裏面設置一個volatile變量,經過修改這個變量來實現。thread