gpt4 book ai didi

java - 中断异常 : what causes it?

转载 作者:太空狗 更新时间:2023-10-29 22:45:45 29 4
gpt4 key购买 nike

关于 Java 的 InterruptedException 有一些有趣的问题和答案。 ,例如 The Cause of InterruptedExceptionHandling InterruptedException in Java .但是,他们都没有告诉我 InterruptedException 的可能来源。

像 SIGTERM、SIGQUIT、SIGINT 这样的操作系统信号呢?在命令行中按 CTRL-C 会产生 InterruptedException 吗?还有什么?

最佳答案

您列出的所有内容都不会产生 InterruptedException .

唯一可以中断线程的是对 Thread#interrupt() 的调用. JLS对此事比较清楚,来自section 17.2.3 :

17.2.3 Interruptions

Interruption actions occur upon invocation of Thread.interrupt, as well as methods defined to invoke it in turn, such as ThreadGroup.interrupt.

参见 the official tutorial on interrupts了解更多信息。具体来说:

A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.

...

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.

这意味着它是一个显式标志,只能通过调用 interrupt() 来设置。 ,而不是由其他未知的外部事件触发。抛出它的各种方法中对异常的描述进一步暗示了这一点,for example (强调我的):

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.


一般而言,中断系统的目的是提供一个通用的、定义良好的框架,以允许线程中断其他线程中的任务(可能是耗时的任务)。虽然您可以在自己的应用程序中使用显式逻辑实现类似的功能,但拥有这种定义良好的机制允许独立类(例如 JDK、其他第三方代码、您自己代码中的其他独立类)以一致的方式提供此功能.

关于处理 InterruptedException 的许多注释和“警告”并不意味着它们可以完全自发地抛出,它们旨在鼓励设计良好的对象,这些对象可以在未知的上下文中使用,其中 interrupt()会被假定工作(所以真的,你确实想假设如果你正在创建在未来情况下将是健壮的可重用对象,它们可以自发地抛出 - 即你永远不能保证你的代码会赢有一天会被希望中断工作的人使用)。

对于快速的一次性项目,您真的不需要担心这些异常的特殊处理,只要您确定您没有调用 interrupt() 即可。并且不调用可以调用 interrupt() 的东西,但要注意从长远来看的影响,尤其是当您最终在其他上下文中重用该代码时。

关于java - 中断异常 : what causes it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856242/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com