为什么在 catch InterruptException 块中调用 Thread.currentThread.interrupt()? [英] Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?

查看:25
本文介绍了为什么在 catch InterruptException 块中调用 Thread.currentThread.interrupt()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要调用catch块中的方法Thread.currentThread.interrupt()?

Why invoke the method Thread.currentThread.interrupt() in the catch block?

推荐答案

这样做是为了保持状态.

当您捕捉到 InterruptedException 并吞下它时,您基本上可以防止任何更高级别的方法/线程组注意到中断.这可能会导致问题.

When you catch the InterruptedException and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.

通过调用Thread.currentThread().interrupt(),您可以设置线程的中断标志,因此更高级别的中断处理程序会注意到它并可以适当地处理它.

By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.

Java 并发实践对此进行了更多讨论第 7.1.3 章:响应中断中的详细信息.它的规则是:

Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:

只有实现线程中断策略的代码才能吞下中断请求.通用任务和库代码永远不应该吞下中断请求.

Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

这篇关于为什么在 catch InterruptException 块中调用 Thread.currentThread.interrupt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆