1、中斷信號Interrupt
1.如果線程處於阻塞狀態會立馬退出阻塞並拋出InterruptedException異常,線程可以通過捕獲InterruptedException方法來做一定處理,然後讓線程退出。
2.如果線程處於運行中則不受任何影響繼續運行,僅僅將線程的中斷標記設置爲true。
2、示例代碼
public class ThreadInterruptDemo {
public static void main(String[] args) throws InterruptedException {
// 模擬正常運行發出中斷信號
Thread threadOne = new Thread(new Runnable() {
public void run() {
Thread currentThread = Thread.currentThread();
while (!currentThread.isInterrupted()) {
System.out.println("Thread One 正在運行!");
}
System.out.println("Thread One 正常結束!" + currentThread.isInterrupted());
}
});
// 模擬阻塞線程發出中斷信號
Thread threadTwo = new Thread(new Runnable() {
public void run() {
Thread currentThread = Thread.currentThread();
while (!currentThread.isInterrupted()) {
synchronized (currentThread) {
try {
currentThread.wait();
} catch (Exception e) {
e.printStackTrace(System.out);
System.out.println("Thread Two 由於中斷信號,異常結束!" + currentThread.isInterrupted());
}
}
}
System.out.println("Thread Two 正常結束!" + currentThread.isInterrupted());
}
});
threadOne.start();
threadTwo.start();
Thread.sleep(2);
System.out.println("兩個線程正常運行,現在開始發出中斷信號");
threadOne.interrupt();
threadTwo.interrupt();
}
}