遇到InterruptedException处理注意事项。

本文详细解析了在Java多线程编程中,如何正确处理InterruptedException,尤其是在循环和嵌套方法调用中。通过修改break语句前的代码,确保了线程中断状态能够被正确检测并响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法调用过程中有嵌套调用方法,两个方法中都会出现InterruptedException异常,并且方法中有循环,要让InterruptedException能够正常捕获,需要特殊注意和break的搭配。

public void test1() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            try {
                int rs = test2();
                System.out.println(rs);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw e;
            }
        }
    }

    public int test2() throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            try {
                if (i == 10) {
                    break;
                }
                if (i == 5) {
                    return i;
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw e;
            }
        }
        return -1;
    }

如果在test2中循环发生着,并且刚好执行到满足break条件进去,此时本线程挂起,而且此时别的线程让该线程的interrupted()值为true。要然程序能够抛出InterruptedException必须在break之前调用interrupted()判断方法是否要抛出InterruptedException,如果要要在这里主动抛出,不然方法结束。interrupted()的值就变为false,return不会影响。

正确下方如下:

public void test1() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            try {
                int rs = test2();
                System.out.println(rs);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw e;
            }
        }
    }

    public int test2() throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            try {
                if (i == 10) {
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    break;
                }
                if (i == 5) {
                    return i;
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw e;
            }
        }
        return -1;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值