为什么InterruptedExceptions清除线程的中断状态? [英] Why do InterruptedExceptions clear a thread's interrupted status?

查看:493
本文介绍了为什么InterruptedExceptions清除线程的中断状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果线程在Object.wait()Thread.join()内部时被中断,则会抛出InterruptedException来重置线程的中断状态.即,如果我在Runnable.run():

If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():

while (!this._workerThread.isInterrupted()) {
    // do something
    try {
        synchronized (this) {
            this.wait(this._waitPeriod);
        }
    } catch (InterruptedException e) {
        if (!this._isStopping()) {
            this._handleFault(e);
        }
    }
}

该线程将在调用interrupt()后继续运行.这意味着我必须通过在循环条件下检查自己的停止标志,重新抛出异常或添加break来显式退出循环.

the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.

现在,这不完全是问题,因为此行为已得到充分记录,并且不会阻止我以自己想要的方式进行任何操作.但是,我似乎并不了解其背后的概念:为什么一旦引发异常,就不再将线程视为中断了?如果使用interrupted()而不是isInterrupted()来获得中断状态,也会发生类似的行为,那么该线程也只会出现一次中断.

Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.

我在这里做不同寻常的事情吗?例如,在循环外捕获InterruptedException是否更常见?

Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?

(即使我不是初学者,我也标记了这个初学者",因为在我看来,这似乎是一个非常基本的问题.)

(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)

推荐答案

这个想法是中断应该被处理一次.如果显式的InterruptedException没有清除中断"标志,则大多数InterruptedException的捕获器将必须显式地清除该标志.相反,您可以通过自中断(Thread.currentThread().interrupt())清除"标志. Java的设计师追求的语义是在大多数情况下可以节省击键操作(即,您更想清除标志而不是保留标志).

The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).

这篇关于为什么InterruptedExceptions清除线程的中断状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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