InterruptedException 时应该如何处理

最近项目中开起来sonar的规范扫描, 提示了InterruptedException处理有问题, 所以记录下
 

当前的做法: 

方式A: 什么都不做, 或者 打印异常的堆栈信息, 或者 记录log

==============================================

单线程场景下是不会抛该异常的

==============================================

假设有A,B 共2个线程, B线程希望A停下来

A线程在等待锁/睡眠时, 根据自身的业务来决定, 是真的停下来,  还是忽略异常 继续执行

InterruptedException就是这个信号

1.在使用Future类的get方法时是必须处理InterruptedException, 所以可以看看业务设计上有没有被其他线程中断的逻辑,
如果没有 那直接使用Thread.currentThread().interrupt(); sonar就不会标红
或者打印异常的堆栈信息, 记录log等

如果有, 则看看当前业务的重要性, 不重要的同上; 
重要的业务, 肯定是要做业务表failure状态的更新, 给上下游发通知, 资源释放等操作
(代码层面就是 把异常向上抛, 或者catch内处理 资源释放等操作)

===============================================

如果只打印log
因为InterruptedException异常会清除 中断状态, 所以线程任然会继续执行

        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Thread is interrupted.");
                }
            }
        });

 所以要重新设置中断标记 Thread.currentThread().interrupt();

当while的条件是true 死循环时, 要记得加上return

public class InterruptExample {

    public static void main(String[] args) {


        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Thread is interrupted.");
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        });
        thread.start();

        // 主线程等待一段时间后中断子线程
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值