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()方法产生的异常