Java執行緒的中斷狀態
一般我們在使用執行緒的過程中會遇到中斷一個執行緒的請求,java中有stop、suspend等方法,但被認為是不完全的,所以棄用了,現在在Java中可以通過iterrupt來請求中斷執行緒。
在Java中主要通過三個方法來進行中斷執行緒操作:
(1)interrupt(),進行執行緒中斷操作,將執行緒中的中斷標誌位置位,置為true;
(2)interrupted(),對執行緒中斷識別符號進行復位,重新置為false;
(3)isInterrupt(),檢查中斷識別符號的狀態,ture還是false;
先來看看interrupt()方法,
public class ThreadTest { public static class MyTestRunnable implements Runnable{ @Override public void run() { while (Thread.currentThread().isInterrupted()){ //獲得當前子執行緒的狀態 System.out.println("停止"); } } public static void main(String[] args) { MyTestRunnable myTestRunnable=new MyTestRunnable(); Thread thread=new Thread(myTestRunnable, "Test"); thread.start(); thread.interrupt(); } }
執行後的結果為:
發現他會迴圈列印結果,執行緒仍在不斷執行,說明它並不能中斷執行的執行緒,只能改變執行緒的中斷狀態,呼叫interrupt()方法後只是向那個執行緒傳送一個訊號,中斷狀態已經設定,至於中斷執行緒的具體操作,在程式碼中進行設計。
要怎樣結束這樣的迴圈,在迴圈中新增一個return即可:
public class ThreadTest { public static class MyTestRunnable implements Runnable{ @Override public void run() { while (Thread.currentThread().isInterrupted()){ //獲得當前子執行緒的狀態 System.out.println("停止"); return; } }
現在是執行緒沒有堵塞的情況下,執行緒能夠不斷檢查中斷識別符號,但是如果線上程堵塞的情況下,就無法持續檢測執行緒的中斷狀態,如果在阻塞的情況下發現中斷識別符號的狀態為true,就會在阻塞方法呼叫處丟擲一個InterruptException異常,並在丟擲異常前將中斷識別符號進行復位,即重新置為false;需要注意的是被中斷的執行緒不一定會終止,中斷執行緒是為了引起執行緒的注意,被中斷的執行緒可以決定如何去響應中斷。
如果不知道丟擲InterruptedException異常後如何處理,一般在catch方法中使用Thread.currentThread().isInterrupt()方法將中斷識別符號重新置為true
@Override
public void run() {
try {
sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
下面來看看如何使用interrupt來中斷一個執行緒,首先先看如果不呼叫interrupt()方法:
public static class MyTestRunnable implements Runnable{
private int i;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){
i++;
System.out.println("i = "+i);
//return;
}
System.out.println("停止");
}
}
public static void main(String[] args) {
MyTestRunnable myTestRunnable=new MyTestRunnable();
Thread thread=new Thread(myTestRunnable, "Test");
thread.start();
}
}
結果為:
可以看出在沒有呼叫interrupt方法將中斷識別符號置為ture的時候,執行緒執行的判斷是迴圈中的方法所以是迴圈列印,下面再看添加了interrupt方法後的結果:
public static void main(String[] args) {
MyTestRunnable myTestRunnable=new MyTestRunnable();
Thread thread=new Thread(myTestRunnable, "Test");
thread.start();
thread.interrupt();
}
}
因為中斷識別符號被置為了true所以執行的是下面的語句,然後執行緒結束。