1. InterruptedException異常概述
當一個方法後面聲明可能會拋出InterruptedException 異常時,說明該方法是可能會花一點時間,但是可以取消的方法。
拋InterruptedException的代表方法有:
1. Java.lang.Object 類的 wait 方法
2. java.lang.Thread 類的 sleep 方法
3. java.lang.Thread 類的 join 方法
-- 需要花點時間的方法
執行wait方法的線程,會進入等待區等待被notify/notify All。在等待期間,線程不會活動。
執行sleep方法的線程,會暫停執行參數內所設定的時間。
執行join方法的線程,會等待到指定的線程結束為止。
因此,上面的方法都是需要花點時間的方法。
-- 可以取消的方法
因為需要花時間的操作會降低程式的響應性,所以可能會取消/中途放棄執行這個方法。
這裡主要是通過interrupt方法來取消。
1. sleep方法與interrupt方法
interrupt方法是Thread類的執行個體方法,在執行的時候並不需要擷取Thread執行個體的鎖定,任何線程在任何時刻,都可以通過線程執行個體來調用其他線程的interrupt方法。
當在sleep中的線程被調用interrupt方法時,就會放棄暫停狀態,並拋出InterruptedException異常,這樣一來,線程的控制權就交給了捕捉這個異常的catch塊了。
2. wait方法和interrupt方法
當線程調用wait方法後,線程在進入等待區時,會把鎖定接觸。當對wait中的線程調用interrupt方法時,會先重新擷取鎖定,再拋出InterruptedException異常,擷取鎖定之前,無法拋出InterruptedException異常。
3. join方法和interrupt方法
當線程以join方法等待其他線程結束時,一樣可以使用interrupt方法取消。因為join方法不需要擷取鎖定,故而與sleep一樣,會馬上跳到catch程式塊
-- interrupt方法幹了什麼。
interrupt方法其實只是改變了中斷狀態而已。
而sleep、wait和join這些方法的內部會不斷的檢查中斷狀態的值,從而自己拋出InterruptEdException。
所以,如果線上程進行其他處理時,調用了它的interrupt方法,線程也不會拋出InterruptedException的,只有當線程走到了sleep, wait, join這些方法的時候,才會拋出InterruptedException。若是沒有調用sleep, wait, join這些方法,或者沒有線上程裡自己檢查中斷狀態,自己拋出InterruptedException,那InterruptedException是不會拋出來的。
isInterrupted方法,可以用來檢查中斷狀態
Thread.interrupt方法,可以用來檢查並清除中斷狀態,interrupt方法只能中斷正在阻塞的線程而不對正在運行中的線程無作用。
2. 如何中斷一個線程:
1. 使用共用變數(shared variable)發出訊號,告訴線程必須停止正在啟動並執行任務。線程必須周期性的核查這一變數(尤其在冗餘操作期間),然後有秩序地中止任務。
package ThreadLocalTest;public class TestCase extends Thread {volatile boolean stop = false;public static void main(String[] args) throws InterruptedException {TestCase thread = new TestCase();System.out.println("Starting thread...");thread.start();Thread.sleep(3000);System.out.println("Asking thread to stop...");thread.stop = true;Thread.sleep(3000);System.out.println("Stopping application...");}public void run() {while (!stop) {System.out.println("Thread is running...");long time = System.currentTimeMillis();while ((System.currentTimeMillis() - time < 1000) && (!stop)) {}}System.out.println("Thread exiting under request...");}}
Starting thread...Thread is running...Thread is running...Thread is running...Thread is running...Asking thread to stop...Thread exiting under request...Stopping application...
2. 對於有可能被阻塞的方法,正確的停止線程方式是設定共用變數,並調用interrupt()(注意變數應該先設定)。 如果線程沒有被阻塞,這時調用interrupt()將不起作用;否則,線程就將得到異常(該線程必須事先預備好處理此狀況),接著逃離阻塞狀態。在任何一種情況中,最後線程都將檢查共用變數然後再停止。Listing C這個樣本描述了該技術。
package ThreadLocalTest;public class ThreadBasic extends Thread {volatile static boolean stop = false;public static void main(String[] args) throws InterruptedException {ThreadBasic thread = new ThreadBasic();System.out.println("Starting thread...");thread.start();Thread.sleep(1000);System.out.println("Asking thread to stop...");stop=true;thread.interrupt();Thread.sleep(3000);System.out.println("Stopping application...");}public void run() {while(!stop){System.out.println("Thread running...");try {Thread.sleep(3000);} catch (InterruptedException e) {System.out.println("Thread interrupted...");}System.out.println("Thread exiting under request...");}}}
Starting thread...Thread running...Asking thread to stop...Thread interrupted...Thread exiting under request...Stopping application...
3.如何處理InterruptedException異常
1. 不捕捉,將它傳遞給調用者
2. 捕捉後恢複中斷狀態
有時候拋出 InterruptedException 並不合適,例如當由 Runnable 定義的任務調用一個可中斷的方法時,就是如此。在這種情況下,不能重新拋出InterruptedException,但是您也不想什麼都不做。當一個阻塞方法檢測到中斷並拋出InterruptedException 時,它清除中斷狀態。如果捕捉到 InterruptedException 但是不能重新拋出它,那麼應該保留中斷髮生的證據,以便調用棧中更高層的代碼能知道中斷,並對中斷作出響應。該任務可以通過調用 interrupt() 以 “重新中斷” 當前線程來完成,如清單 3 所示。至少,每當捕捉到InterruptedException 並且不重新拋出它時,就在返回之前重新中斷當前線程。
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } }}
中斷線程
處理InterruptedException
InterruptedException介紹