为了账号安全,请及时绑定邮箱和手机立即绑定

线程的中断状态

线程的中断状态

慕桂英4014372 2018-08-10 18:34:16
void mySubTask(){try{sleep(delay)}catch(InterruptedException e){Thread.currentThread.interrupt();} }这串代码是《java核心技术》中并发一节的。14.2中断线程,634页。当线程处于阻塞状态时,对其发送一个中断信号,会导致抛出InterruptedException异常。那么以上代码,在捕捉了这个异常后为什么还要对其设置中断状态呢?换句话说,这里设置中断状态,意义何在呢?
查看完整描述

2 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

抛出异常后会清除中断标记位,调用Thread.currentThread.interrupt()重新设置中断状态,让调用方知道是由于中断才结束线程的。

比如你上面的代码,sleep响应了中断,当线程在seep中的时候,如果这个时候有中断的请求,就会抛出InterruptedException异常,并且清除中断状态,所以我们有时候需要再置为中断状态(其实就是需要保持这个中断状态)。

public class Test {    public static int count = 0;    public static void main(String[] args) throws InterruptedException {
        Thread th = new Thread(){
            @Override            public void run() {                while(true){                    if(Thread.currentThread().isInterrupted()){//(1)
                        System.out.println("Thread Interrupted");                        break;
                    }
                    System.out.println("invoking!!!");                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.out.println("Interruted When Sleep");                        //抛出异常后会清除中断标记位,所以需要重新设置中断状态,让(1)出的代码可以检测到中断结束线程
                        Thread.currentThread().interrupt();
                    }

                }
            }
        };
        th.start();
        Thread.currentThread().sleep(1000);
        th.interrupt();
    }
}
打印结果:
invoking!!!
Interruted When Sleep
Thread Interrupted


查看完整回答
反对 回复 2018-08-12
?
暮色呼如

TA贡献1853条经验 获得超9个赞

wait中抛出InterruptedException 会消耗此线程的中断状态

再中断一次可能是为了向外传递?


查看完整回答
反对 回复 2018-08-12
  • 2 回答
  • 0 关注
  • 730 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号