interrupt() 方法只是改變中斷狀態而已,它不會中斷一個正在運行的線程。
這一方法實際完成的是,給受阻塞的線程發出一個中斷信號,這樣受阻線程就得以退出阻塞的狀態。
更確切的說,如果線程被Object.wait, Thread.join和Thread.sleep三種方法之一阻塞,此時調用該線程的interrupt()方法,那么該線程將拋出一個 InterruptedException中斷異常(該線程必須事先預備好處理此異常),從而提早地終結被阻塞狀態。如果線程沒有被阻塞,這時調用 interrupt()將不起作用,直到執行到wait(),sleep(),join()時,才馬上會拋出 InterruptedException。
示例代碼如下:
public class InterruptTest { public static void main(String[] args) { for(int i=0;i<5;i++){ Thread thread=new Thread( new InterruptThread()); thread.start(); thread.interrupt(); } } static class InterruptThread implements Runnable { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("線程處於阻塞狀態時,中斷線程,就會拋出異常。"); e.printStackTrace(); } } } }
運行的其中一種結果:
線程處於阻塞狀態時,中斷線程,就會拋出異常。 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.thread.InterruptTest$InterruptThread.run(InterruptTest.java:17) at java.lang.Thread.run(Thread.java:748)
參考博客:https://blog.csdn.net/zhangliangzi/article/details/52485319
