Thread.interrupt()是邪恶的吗? [英] Is Thread.interrupt() evil?

查看:103
本文介绍了Thread.interrupt()是邪恶的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

队友做出以下声明:


Thread.interrupt()本质上是破碎的,应该(几乎)永远不会被使用。

"Thread.interrupt() is inherently broken, and should (almost) never be used".

我试图理解为什么会这样。

I am trying to understand why this is the case.

这是一个已知的最佳做法,永远不要使用 Thread.interrupt()?你能提供证据证明它为什么会被破坏/错误,不应该用于编写强大的多线程代码吗?

Is it a known best practice never to use Thread.interrupt()? Can you provide evidence why it is broken / buggy, and should not be used for writing robust multithreaded code?

注意 - 我不感兴趣在这个问题中,如果从设计防腐剂中漂亮。我的问题是 - 它是否有错误?

Note - I am not interested in this question if it's "pretty" from a design preservative. My question is - is it buggy?

推荐答案

短版本:


这是一个已知的最佳做法,永远不会使用
使用Thread.interrupt()吗?

Is it a known best practice never to use Thread.interrupt()?

否。


你能提供吗?
证据为什么它被破坏/ buggie,
并且不应该用于编写
强大的多线程代码?

Can you provide evidence why it is broken / buggie, and should not be used for writing robust multithreaded code?

反之亦然:它对于多线程代码至关重要。

The opposite is true: it is critical for multithreaded code.

参见 Java Concurrency in Practice 的例子。

更长的版本:

在这里,我们在一个特定的地方使用这种方法:处理 InterruptedExceptions 。这可能看起来有点奇怪,但这就是代码中的样子:

Around here, we use this method in one specific place: handling InterruptedExceptions. That may seem a little strange but here's what it looks like in code:

try {
    // Some code that might throw an InterruptedException.  
    // Using sleep as an example
    Thread.sleep(10000);
} catch (InterruptedException ie) {
    System.err.println("Interrupted in our long run.  Stopping.");
    Thread.currentThread().interrupt();
}

这对我们来说有两件事:

This does two things for us:


  1. 避免吃掉中断异常。 IDE自动异常处理程序总是为您提供类似 ie.printStackTrace(); 和一个轻松的TODO:有用的东西需要去这里!评论。

  2. 它会恢复中断状态,而不会在此方法上强制执行检查异常。如果您正在实现的方法签名没有抛出InterruptedException 子句,则这是传播该中断状态的另一种选择。

  1. It avoids eating the interrupt exception. IDE auto-exception handlers always provide you with something like ie.printStackTrace(); and a jaunty "TODO: Something useful needs to go here!" comment.
  2. It restores the interrupt status without forcing a checked exception on this method. If the method signature that you're implementing does not have a throws InterruptedException clause, this is your other option for propagating that interrupted status.

一位意见提供者建议我应该使用未经检查的异常强制线程死亡。这假设我事先知道突然杀死线程是正确的事情。我不。

A commenter suggested that I should be using an unchecked exception "to force the thread to die." This is assuming that I have prior knowledge that killing the thread abruptly is the proper thing to do. I don't.

在上面引用的列表之前的页面上引用JCIP的Brian Goetz:

To quote Brian Goetz from JCIP on the page before the listing cited above:


任务不应该假设其
执行线程的中断策略,除非明确设计为在具有特定中断策略的
服务中运行。

A task should not assume anything about the interruption policy of its executing thread unless it is explicitly designed to run within a service that has a specific interruption policy.

例如,假设我这样做了:

For example, imagine that I did this:

} catch (InterruptedException ie) {
    System.err.println("Interrupted in our long run.  Stopping.");
    // The following is very rude.
    throw new RuntimeException("I think the thread should die immediately", ie);
}

我会宣布这一点,不管剩下的其他通话是否有其他义务堆栈和关联状态,此线程现在需要死亡。我会试图偷偷过去所有其他的catch块并说明清理代码以直接线程死亡。更糟糕的是,我会消耗线程的中断状态。上游逻辑现在必须解构我的异常以试图弄清楚是否存在程序逻辑错误,或者我是否试图在隐藏的包装器中隐藏已检查的异常。

I would be declaring that, regardless of other obligations of the rest of the call stack and associated state, this thread needs to die right now. I would be trying to sneak past all the other catch blocks and state clean-up code to get straight to thread death. Worse, I would have consumed the thread's interrupted status. Upstream logic would now have to deconstruct my exception to try to puzzle out whether there was a program logic error or whether I'm trying to hide a checked exception inside an obscuring wrapper.

例如,以下是团队中其他人立即要做的事情:

For example, here's what everyone else on the team would immediately have to do:

try {
    callBobsCode();
} catch (RuntimeException e) { // Because Bob is a jerk
    if (e.getCause() instanceOf InterruptedException) {
        // Man, what is that guy's problem?
        interruptCleanlyAndPreserveState();
        // Restoring the interrupt status
        Thread.currentThread().interrupt();
    }
}

中断状态比任何特定<$更重要C $ C> InterruptException 。有关具体示例的原因,请参阅javadoc Thread.interrupt()

The interrupted state is more important than any specific InterruptException. For a specific example why, see the javadoc for Thread.interrupt():


如果在调用wait()时阻止此线程,请等待(long),
或Object类的wait(long,int)方法,或者join(),
join(long),join(long,int),sleep(long)或者sleep(long,int),这个类的
方法,然后它的中断状态将被清除,
会收到InterruptedException。

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

正如您所看到的,可以在处理中断请求时创建和处理多个InterruptedException,但仅在保留该中断状态时才会创建和处理。

As you can see, more than one InterruptedException could get created and handled as interrupt requests are processed but only if that interrupt status is preserved.

这篇关于Thread.interrupt()是邪恶的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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