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回答
-
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一样清除中断状态。
022019-09-20
相似问题