若是拋出異常,中斷狀態設置爲false。ide
public class InterruptThread extends Thread { @Override public void run() { while (true) { } } public static void main(String[] args) throws InterruptedException { InterruptThread thread = new InterruptThread(); thread.start(); System.out.println(thread.getState()); sleep(1000); thread.interrupt(); System.out.println(thread.getState()); System.out.println(thread.isInterrupted()); } }
運行結果以下
能夠看出,雖然中斷狀態是true了,可是程序依然在運行,因此interrupt並無強制中斷線程。spa
public class InterruptThread2 extends Thread { @Override public void run() { while (!isInterrupted()) { } System.out.println("已中斷"); } public static void main(String[] args) throws InterruptedException { InterruptThread2 thread = new InterruptThread2(); thread.start(); System.out.println(thread.getState()); sleep(1000); thread.interrupt(); System.out.println(thread.getState()); System.out.println(thread.isInterrupted()); } }
運行結果以下:
跟例子1的區別是,經過判斷中斷狀態,來處理咱們本身的業務邏輯,這樣的設計,給程序帶來了極大的利靈活性。線程
public class InterruptWait extends Thread { @Override public void run() { waitFun(); } public synchronized void waitFun(){ try { wait(); } catch (InterruptedException e) { System.out.println("打擾我等待了"); } } public static void main(String[] args) throws InterruptedException { InterruptWait thread = new InterruptWait(); thread.start(); System.out.println(thread.getState()); sleep(1000); thread.interrupt(); sleep(1000); System.out.println(thread.getState()); System.out.println(thread.isInterrupted()); sleep(1000); System.out.println(thread.getState()); } }
運行結果以下:
中斷wait方法,這裏須要注意的是,拋出異常後,中斷狀態變成false。設計
public class InterruptWait extends Thread { @Override public void run() { waitFun(); } public synchronized void waitFun(){ try { wait(); } catch (InterruptedException e) { System.out.println("打擾我等待了"); } } public static void main(String[] args) throws InterruptedException { InterruptWait thread = new InterruptWait(); thread.start(); System.out.println(thread.getState()); sleep(1000); thread.interrupt(); sleep(1000); System.out.println(thread.getState()); System.out.println(thread.isInterrupted()); sleep(1000); System.out.println(thread.getState()); } }
運行結果以下:
結果同上,拋出異常後,中斷狀態變成false。3d
public class InterruptSync extends Thread { @Override public void run() { syncFun(); } public static synchronized void syncFun() { while (true) { } } public static void main(String[] args) throws InterruptedException { InterruptSync thread = new InterruptSync(); InterruptSync thread2 = new InterruptSync(); thread.start(); sleep(1000); thread2.start(); sleep(1000); System.out.println(thread.getState()); System.out.println(thread2.getState()); thread2.interrupt(); sleep(1000); System.out.println(thread2.getState()); System.out.println(thread2.isInterrupted()); } }
運行結果以下:
沒有拋異常,結果同例子1。code