InterruptedException异常处理方式

31 篇文章 2 订阅

InterruptedException 是 Java 中的一个 checked 异常,它表示线程被中断了,通常由 interrupt() 方法触发。

一、上抛

采用异常上抛的方式,此种方式较为简单,层层上抛即可!这也是**“恢复中断”的一种方式,但若是调用堆栈过深,则代码侵入性问题就会变得更加明显。**可以改用Thread.currentThread().interrupt()方式恢复中断。

为什么要层层上抛?

因为“InterruptedException 是 Java 中的一个 checked 异常”,编码阶段必须处理,也可以catch InterruptedException 改用 throw new RuntimeException(e)异常抛出,但这会导致上层调用逻辑无法正确感知“线程中断”动作,仅仅当做普通异常处理。

public void handle() throws InterruptedException

二、响应中断或恢复中断

在处理 InterruptedException 时,通常应该做两件事情响应中断或恢复中断。

1. 响应中断

响应中断是指当线程被中断时,需要对此进行响应并做出一些处理。响应中断通常通过捕获 InterruptedException 异常并在 catch 语句块中进行处理来实现。处理方式通常是将线程的中断状态标志位重新设置为 false,以便后续代码可以正常执行。
例如,在一个生产消费模型中,当生产者生产完毕后,可以将标志位设置为 true,此时消费者线程在处理完当前队列中的任务后,可以检查标志位的状态并结束线程的执行。

  • 代码示例
public class MyTask implements Runnable {
    @Override
    public void run() {
        // Thread.currentThread().isInterrupted() 不会清除中断标志位 Thread#interrupted 会清除中断标志位
        while (!Thread.currentThread().isInterrupted()) {
            // do something
        }
        // 以下内容正常输出
        System.out.println("Task is interrupted.");
    }
}


public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread taskThread = new Thread(new MyTask());
        taskThread.start();
        Thread.sleep(1000); // 等待1秒钟
        taskThread.interrupt(); // 发送中断请求
    }
}

2. 恢复中断

**恢复中断是指在处理完中断异常后,需要将线程的中断状态标志位重新设置为 true,以便后续代码能够检查到线程被中断的状态。**恢复中断通常使用 Thread.currentThread().interrupt() 方法来实现,可以确保线程的中断状态被正确地恢复。
值得注意的是,如果在线程的中断异常处理块中没有使用 Thread.currentThread().interrupt() 方法进行中断状态的恢复,那么线程的中断状态仍然处于中断状态,后续任何需要响应中断的代码都将无法正常执行,因为中断状态一直处于中断状态,直到下一个线程阻塞或者退出。
因此,在处理 InterruptedException 异常时,应该及时恢复中断状态,以确保后续代码可以正常响应中断。

  • 代码示例
public class MyTask implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 重新设置中断标志位
            }
        }
         // 以下内容正常输出
        System.out.println("Task is interrupted.");
    }
}


public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread taskThread = new Thread(new MyTask());
        taskThread.start();
        Thread.sleep(500); // 等待0.5秒钟
        taskThread.interrupt(); // 发送中断请求
    }
}
  • sleep示例
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;

Thread#sleep中写道“sleep期间,若任何线程中断当前线程,则会抛出InterruptedException异常并重置中断标志位标识为初始值(isInterrupted=false)

try {
    // 可能抛出 InterruptedException 异常的代码
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // 响应中断,并重新设置中断标志位
    Thread.currentThread().interrupt();
}

3. 最佳实践

public class MyTask implements Runnable {
    @Override
    public void run() {
        // 轮询中断标志位控制循环逻辑是否终止
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000);
                System.out.println(1);
            } catch (InterruptedException e) {
                System.out.println(2);
                // 重新设置中断标志位
                Thread.currentThread().interrupt(); 
                // 上抛异常 通过Caused by分情况处理
                // throw new RuntimeException(e);
            } finally {
                System.out.println(3);
            }
        }
        
        // 若上抛异常,下面内容不会打印
        // 线程中断了,下面内容才会打印(也可以用于控制代码执行逻辑,选择中断时执行例如线程池资源释放,还是正常时执行)
        if (Thread.currentThread().isInterrupted()) {
            System.out.println("线程池资源释放中...");
        }
        
        // 若上抛异常,下面内容不会打印
        System.out.println("Task is interrupted.");
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬山境KL攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值