概述
中斷代表線程狀態, 每個線程都會有一箇中斷狀態, 用boolean表示, 初始值爲false, 而線程的中斷其實就是修改這個中斷狀態爲true的過程.
中斷只是一個狀態, 並不能決定線程的運行.
- 假設當前線程處於阻塞等待狀態, 例如調用了wait()、join()、sleep()方法後, 調用線程的interrupt()方法, 此時中斷狀態被置爲true, 線程會立馬退出阻塞並拋出InterruptedException, 拋出異常後會將中斷標誌位重新設爲false.
- 假設當前線程處於運行狀態, 在調用線程的interrupt()方法後, 此時中斷狀態被置爲true, 但是線程並不會結束運行, 需要在線程的具體執行邏輯中調用isInterrupted()檢測線程中斷狀態, 主動響應中斷.
我們來看下Thread類中有關中斷操作相關的方法, 具體功能已經在代碼註釋中說明.
// 設置一個線程的中斷狀態爲true
public void interrupt() {}
// 檢測線程中斷狀態,處於中斷狀態返回true, 該方法不會清理中斷標誌位
public boolean isInterrupted() {
return isInterrupted(false);
}
// 注意⚠️:這是個靜態方法,檢測是否中斷
// 注意⚠️:這個方法返回中斷狀態的同時,會將線程中斷標誌位重置爲false
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
// native方法,ClearInterrupted表示是否清理中斷標誌位
private native boolean isInterrupted(boolean ClearInterrupted);
使用線程中斷來終止線程運行
方法一:通過拋出InterruptedException異常來終止線程運行
public class Test1 {
public static void main(String[] args) throws Exception {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(1000);
myThread.interrupt();
}
private static class MyThread extends Thread {
int i = 0;
@Override
public void run() {
while (true) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("線程被中斷, 中斷狀態 = " + this.isInterrupted());
return;
}
i++;
}
}
}
}
方法二:通過檢測線程中斷狀態終止程序運行
public class Test2 {
public static void main(String[] args) throws Exception {
Thread myThread = new MyThread();
myThread.start();
Thread.sleep(1000);
myThread.interrupt();
}
private static class MyThread extends Thread {
int i = 0;
@Override
public void run() {
//while (!this.isInterrupted()) {
// System.out.println(i);
//}
while (!Thread.interrupted()) {
System.out.println(i);
}
}
}
}