gpt4 book ai didi

java - 为什么 Thread 的子类可以吞下 InterruptedException?

转载 作者:搜寻专家 更新时间:2023-11-01 01:39:22 25 4
gpt4 key购买 nike

在 Brian Goetz 的 article on how to handle InterruptedException 中,一段脱颖而出:

The one time it's acceptable to swallow an interrupt is when you know the thread is about to exit. This scenario only occurs when the class calling the interruptible method is part of a Thread, not a Runnable.

我不明白这个。与 Runnable 相关的原因是否可能由线程池处理,而 Thread 是您自己启动的?

最佳答案

基本上。文章中表达的担忧是,如果您吞下中断异常,那么调用堆栈中更高层的代码将不知道中断,可能会导致不良行为。如果你启动了线程,那么你就知道在调用堆栈中没有更高层的东西关心被中断,这个线程不会继续活在线程池中,所以让线程死掉。

我讨厌 InterruptedException,我认为它给检查的异常带来了坏名声,而本文不会改变这个观点。如果这个异常传递到调用堆栈非常重要,Runnable.run() 应该在方法声明中声明它,这样您就可以简单地重新抛出它,或者它应该是一个未经检查的异常,原因与 SecurityException 是一个未经检查的异常相同异常。

我更喜欢的设计是,如果你想知道这些方法是否被中断,它们将返回一个 boolean 值,但这篇文章确实说明了这不一定实用。

关于java - 为什么 Thread 的子类可以吞下 InterruptedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/885850/

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