interrupt()方法不會中斷一個正在運行的線程,它用於提前退出線程的阻塞狀態,也就是說當線程通過Object.wait() / Thread.sleep() / Thread.join() / 方法進入阻塞狀態後,如果調用線程中斷方法,該線程會收到一個InterruptedException中斷異常,可以在catch中編寫自己需要的代碼。
public class InterruptThread {
public static void main(String[] args){
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try{
long time = System.currentTimeMillis();
while(System.currentTimeMillis()- time <1000){
}
System.out.println("T1_normal");
}catch(Exception e){
System.out.println("T1_Exception e="+e);
}
}
},"t1");
t1.start();
t1.interrupt();
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
System.out.println("T2_sleep_normal");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("T2_sleep_Exception e="+e);
}
}
},"t2");
t2.start();
t2.interrupt();
Thread t4 = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
this.wait(1000);
System.out.println("T4_wait_normal");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("T4_wait_Exception e="+e);
}
}
},"t4");
t4.start();
t4.interrupt();
Thread t5 = new Thread(new Runnable(){
@Override
public synchronized void run() {
// TODO Auto-generated method stub
try {
this.wait(1000);
System.out.println("T5_wait_normal");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("T5_wait_Exception e="+e);
}
}
},"t5");
t5.start();
t5.interrupt();
try{
t5.start();
System.out.println("T5_again_wait_normal");
}catch(Exception e){
System.out.println("T5_again_wait_Exception e="+e);
}
}
}
打印出來的log(順序隨機):
T2_sleep_Exception e=java.lang.InterruptedException: sleep interrupted
T4_wait_Exception e=java.lang.IllegalMonitorStateException
T5_again_wait_Exception e=java.lang.IllegalThreadStateException
T5_wait_Exception e=java.lang.InterruptedException
T1_normal
1.線程T1:
log:T1_normal
可以看出interrupt()方法不會中斷正在執行的線程。
2.線程T2:
log:T2_sleep_Exception e=java.lang.InterruptedException: sleep interrupted
可以看出sleep中斷
3.線程T4:
log:T4_wait_Exception e=java.lang.IllegalMonitorStateException
這個是在沒有被鎖定的對象中,調用wait()方法產生的異常
4.線程T5:
log:T5_wait_Exception e=java.lang.InterruptedException
wait中斷
log:
T5_again_wait_Exception e=java.lang.IllegalThreadStateException
重複調用線程的start()方法產生的異常