storage.put()阻塞后响应中断疑问

来源:5-12 停止失效

水桶一号

2019-09-19

前面小结的讲解中,sleep期间被中断java会将中断状态更改,
所以需要在catch中调用Thread.currentThread().interrupt() 恢复中断状态后才能再次通过Thread.currentThread().isInterrupted()判断,但是本小节中storage.put()阻塞响应中断后并未在catch中调用Thread.currentThread().interrupt()恢复中断状态,我想请问老师:storage.put()阻塞响应中断后不会像sleep一样更改中断状态吗?

写回答

1回答

悟空

2019-09-19

class Producer implements Runnable {

    public volatile boolean canceled = false;

    BlockingQueue storage;

    public Producer(BlockingQueue storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        System.out.println("生产者开始生产数据了");
        int num = 0;
        try {
            while (!Thread.currentThread().isInterrupted()) {
                if (num % 100 == 0) {
                    storage.put(num);
                    System.out.println(num + "是100的倍数,被放到仓库中了。");
                }
                num++;
            }
        } catch (InterruptedException e) {
            System.out.println("生产者收到中断信号");
        } finally {
            System.out.println("生产者结束运行");
        }
    }
}

这里put期间收到中断信号,就被catch住,然后就整个跳出while循环,停止运行了。storage.put()阻塞响应中断后,也会像sleep一样清除中断状态。

0
2
悟空
回复
水桶一号
说得没错,这里会加!Thread.currentThread().isInterrupted()是因为历史原因,在代码迭代的过程中,需要先展示出无法检测到中断发生的情况(因为在put中阻塞了却没人唤醒),所以加了!Thread.currentThread().isInterrupted()让这个检测更明显。当明确了put()阻塞可以响应中断后,就可以把!Thread.currentThread().isInterrupted()去掉的。
2019-09-20
共2条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程