An interrupt is an indication to a thread that it should stop what it is doing and do something else.html
中斷(interupt)是一個指示,指示一個線程中止正在作的事情,並作一些其餘的事情。java
咱們一般使用 中斷 去終止線程oracle
調用 interrupt()
,向線程發送 interrupt 指示。this
若是一個線程內,頻繁的調用一個能夠 throw InterruptedException
的方法,在接收到 interrupt 指示時,拋出 InterruptedException 。只須要 catch 該異常,並 return,便可退出 run 方法 —— 即終止了線程。線程
for (int i = 0; i < importantInfo.length; i++) { // Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { // We've been interrupted: no more messages. return; } // Print a message System.out.println(importantInfo[i]); }
Thread 的不少方法均可以 throw InterruptedException
,好比 Thread.sleep 方法。當獲取到 interrupt 指示時,這些方法將拋出異常。捕獲這個異常,並 return ,便可中斷線程。code
若是一個線程會運行很長時間,且沒有調用任何能夠 throw InterruptedException
的方法,怎麼辦?必須按期運行 Thread.interrupted 方法,當獲取 interrupt 指令時返回 true
htm
for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { // We've been interrupted: no more crunching. return; } }
若是項目比較複雜的話,throw new InterruptedException
更有意義get
if (Thread.interrupted()) { throw new InterruptedException(); }
The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.input
interrupt 機制的實現,使用了一個內部的flag,用於標識 interrupt status 。it
調用 靜態方法 Thread.interrupted(用於檢查當前 Thread 是否 interrupt),interrupt status 會被清除。
調用 非靜態方法 isInterrupted(用於一個 Thread 查詢另外一個 Thread 是否 interrupt),不會清除 interrupt status。