JAVA线程interrupt中断的正确操作

java线程操作中,会常用到interrupt这种中断处理,但是发现下层办法中断,上层方法依然感受不到线程处于中断,导致代码一直在执行,并没有停止,于是查看原理,发现下层方法里,虽然中断了,但是中断状态被下层的异常处理了,但是上层方法无法感知,故做此文记录

错误示例

public class RightWayInterruptThreadPro1 implements  Runnable{


    public  void otherMethod() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true&&!Thread.currentThread().isInterrupted()){
            System.out.println("go");
            try {
                otherMethod();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("插入日志");
            }
        }
    }

    public static void main(String[] args) {
        Thread thread=new Thread(new RightWayInterruptThreadPro1());
        thread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

效果如下,发现虽然下层方法已经中断,上次方法这里依然获取的线程中断状态为false,所以程序一直还在执行,并没有被上层捕获到异常状态信息,想做日志操作都不行

正确示例,通过让下层方法签名抛出异常的方法,能让上层方法捕获到打断异常,进行进行日志操作

public class RightWayInterruptThreadPro1 implements  Runnable{

    /**
     * 利用方法签名的方式抛出异常,让上层方法得到此异常进行处理
     * @throws InterruptedException
     */
    public  void otherMethod() throws  InterruptedException{
        Thread.sleep(1000);
    }

    @Override
    public void run() {
        while (true&&!Thread.currentThread().isInterrupted()){
            System.out.println("go");
            try {
                otherMethod();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("插入日志");
            }
        }
    }

    public static void main(String[] args) {
        Thread thread=new Thread(new RightWayInterruptThreadPro1());
        thread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

效果图如下

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值