interrupt()
修改線程的中斷標(biāo)識(shí),在wait、join和sleep方法下的會(huì)拋出異常InterruptedException,線程的中斷狀態(tài)會(huì)被jvm自動(dòng)清除,線程的中斷標(biāo)志重新設(shè)置為false
isInterrupted()
只是簡(jiǎn)單的查詢中斷狀態(tài)
interrupted()
靜態(tài)方法。如果當(dāng)前線程被中斷,你調(diào)用interrupted方法,第一次會(huì)返回true。然后,當(dāng)前線程的中斷狀態(tài)被方法內(nèi)部清除了,設(shè)置為true。那么第二次調(diào)用時(shí)就會(huì)返回false。
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);
異常處理
wait、join和sleep方法下的會(huì)拋出異常,將線程的中斷標(biāo)志重新設(shè)置為false
等待鎖的時(shí)候不拋出異常
public class Main{
public static byte[] lock= new byte[1];
public static void main(String[] args) {
Thread th1 = new Thread("1"){
public void run(){
synchronized(lock){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread th2 = new Thread("2"){
public void run(){
synchronized(lock){
System.out.println(Thread.currentThread().isInterrupted());
}
}
};
th1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
th2.start();
th2.interrupt();
}
}
//輸出
1
true