1.中斷原理
java中斷並非直接中斷線程的運行,中斷只是一種協作機制,每個線程底層都保留一箇中斷標誌符,程序可以調用中斷方法,但是是否真正的中斷還是依賴於應用程序本身的處理,中斷有對應2種情況,在線程阻塞時,對於某些特別的阻塞,例如Thread方法的sleep,Object的wait方法,以及一些nio的阻塞,阻塞隊列的take方法等,如果在阻塞的狀態下調用interrupt()方法,會導致拋出InterruptedException異常,並重置其中斷狀態,即爲false。而在另一些常規的IO阻塞和同步阻塞,設置中斷,都只會改變其中斷狀態,程序可以處理,也可以不處理。
下面的三個方法都是Thread類的。
中斷相關方法 | 作用 |
---|---|
interrupt() | 設置線程中斷的唯一方法 |
interrupted() | 靜態方法,獲取當前線程是否中斷的方法,獲取之後中斷狀態將會被重置,例如調用interrupt()方法,再調用interrupted()方法會返回true,第二次調用會返回false,因爲中斷的狀態被重置了。 |
isInterrupted() | 返回線程的中斷狀態,中斷不會被此方法改變。 |
2.實例
package com.thread.study;
import com.util.GeneryUtil;
public class InterruptTest implements Runnable{
@Override
public void run() {
try {
while(true) {
}
} catch (Exception e) {
GeneryUtil.outputConsole("interrupt Exception");
}
}
public static class InterruptTest2 implements Runnable{
@Override
public void run() {
System.out.println("this is InterruptTest2");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("InterruptedException of InterruptTest2");
e.printStackTrace();
}
}
}
public static class InterruptTest3 implements Runnable{
@Override
public void run() {
System.out.println("this is InterruptTest3");
synchronized (this){
try {
this.wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException of InterruptTest3");
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new InterruptTest());
Thread t2 = new Thread(new InterruptTest2());
Thread t3 = new Thread(new InterruptTest3());
t1.start();
t2.start();
t3.start();
Thread.sleep(3000);
Thread.currentThread().interrupt();
t2.interrupt();
t3.interrupt();
System.out.println("first get interrupt of status of t1:"+Thread.currentThread().interrupted());
System.out.println("second get interrupt of status of t1:"+Thread.currentThread().interrupted());
System.out.println("second get interrupt of status of t1 by isInterrupted's method "+Thread.currentThread().isInterrupted());
}
}