JAVA线程中断Interrupt恢复办法

最近学习了线程中断原理,由于线程在运行中,如果执行了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,说明此事线程的中断被异常捕获机制,清除掉了,于是只能手动设置中断状态,然后让上层方法收到中断感知,收到后自然就停止了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值