为什么吞下InterruptedException确定Thread的子类? [英] Why is swallowing InterruptedException ok for subclasses of Thread?

查看:153
本文介绍了为什么吞下InterruptedException确定Thread的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Brian Goetz的有关如何处理InterruptedException的文章 ,一个段落突出显示:

In Brian Goetz's article on how to handle InterruptedException, one paragraph stands out:


一次可以接受一个中断是当你知道线程即将退出。这种情况只发生在调用interruptible方法的类是Thread的一部分,而不是Runnable的时候。

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是什么你开始自己吗?

I don't get this. Is the reason something to do with the Runnable possibly being handled by a threadpool whereas the Thread is something you start on your own ?

推荐答案

基本上。文章中表达的关注是,如果你吞咽中断异常,那么在堆栈中更高的调用代码将不知道中断,可能导致不良行为。如果你启动线程,那么你知道在调用堆栈中没有什么比较关心被中断的,这个线程不会继续生活在线程池中,所以只是让线程死掉。

Basically. The concern expressed in the article is that if you swallow the interupt exception then calling code higher in the stack won't know about the interuption, possibly causing undesirable behavior. If you start the thread, then you know there is nothing higher in the call stack that cares about being interupted, this thread will not continue to live in a thread pool, so just let the thread die.

我讨厌InterruptedException,我认为它给检查异常一个坏名字,并且本文不改变这个角度。如果这是非常重要的,这个异常传递到调用堆栈,Runnable.run()应该在方法声明中声明,所以你可以简单地重新抛出它,或者应该是一个未检查的异常,同样的原因SecurityException是未检查异常。

I hate InterruptedException, I think it gives checked exceptions a bad name, and this article doesn't change that perspective. If it was so important that this exception pass up the call stack, Runnable.run() should have it declared in the method declaration so you can simply rethrow it, or it should have been an unchecked exception for the same reason SecurityException is an unchecked exception.

我的首选设计是,如果你想知道,这些方法返回一个布尔值,但是本文确实会必然实用。

My prefered design would be that the methods return a boolean if they were interrupted if you care to know, but this article does make the case that that wouldn't necessarily be practical.

这篇关于为什么吞下InterruptedException确定Thread的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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