最近学习了线程中断原理,由于线程在运行中,如果执行了sleep方法,会被trycatch捕获到,然后会出现中断方法的上层方法捕获不到,于是研究了下,发现下层方法里,中断后,被异常捕获,捕获后把线程中断信号清除了,做此文用来记录下,方面以后查阅
错误代码如下
public class RightWayInterruptPro2 implements Runnable {
@Override
public void run() {
//如果中断了,则跳出执行
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println("收到中断停止执行");
break;
}
reInterrupt();
}
}
private void reInterrupt(){
//模拟内部中断
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().isInterrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread=new Thread(new RightWayInterruptPro2());
thread.start();
try {
//先休眠,然后再让线程中断
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
效果图如下,发现中断后,方法一直在执行,上层方法并没有检测到正常的中断的状态,到此一直不停止程序
正确执行代码
public class RightWayInterruptPro2 implements Runnable {
@Override
public void run() {
//如果中断了,则跳出执行
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println("收到中断停止执行");
break;
}
reInterrupt();
}
}
private void reInterrupt(){
//模拟内部中断
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().isInterrupted());
e.printStackTrace();
//检测中断状态
System.out.println(Thread.currentThread().isInterrupted());
//添加此行代码,因为虽然中断了,线程中断被捕获,然后中断消息也会被清除,
//所以加入Thread.currentThread.interrupt();
//手动恢复中断状态
Thread.currentThread().interrupt();
//检测中断状态是否恢复
System.out.println(Thread.currentThread().isInterrupted());
}
}
public static void main(String[] args) {
Thread thread=new Thread(new RightWayInterruptPro2());
thread.start();
try {
//先休眠,然后再让线程中断
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
效果如下
中断信息在下层抛出,也能看到抛出异常后,线程中断状态为false,说明此事线程的中断被异常捕获机制,清除掉了,于是只能手动设置中断状态,然后让上层方法收到中断感知,收到后自然就停止了