调用Thread.sleep()与*中断状态*设置? [英] Calling Thread.sleep() with *interrupted status* set?

查看:488
本文介绍了调用Thread.sleep()与*中断状态*设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java文档在这一点上并不清楚。如果在调用之前调用 中的中断 Thread.sleep()

The Java documentation is not clear on this point. What happens if you call interrupt on a Thread before it calls Thread.sleep():

        //interrupt reaches Thread here
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            return;
        }

InterruptedException 会被抛出?

请指向相关文档。

推荐答案

是的,它会抛出异常。根据线程的javadoc。睡眠,方法:

Yes, it will throw an exception. According to the javadoc for Thread.sleep, the method:


抛出:
InterruptedException - 如果有任何线程中断了当前线程。抛出此异常时,当前线程的中断状态被清除。

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

在这种情况下,'has'是一种非正式的方式指中断状态。令人遗憾的是它是非正式的 - 如果某个地方的规范应该是精确和明确的,那么它无处不在,但它首先是线程原语。

The 'has' in this case is an informal way of referring to the interrupted status. It's a shame that it is informal - if there's somewhere a spec should be precise and unambiguous, well, it's everywhere, but it's the threading primitives above all.

中断状态机制的作用一般是,如果一个线程在不可中断的情况下收到中断(因为它正在运行),那么中断基本上是等到线程中断,此时它突然导致一个InterruptedException。这是该机制的一个例子。

The way the interrupted status mechanism works in general is if that a thread receives an interruption while it's not interruptible (because it's running), then the interruption is essentially made to wait until the thread is interrupted, at which point it swoops in an causes an InterruptedException. This is an example of that mechanism.

这篇关于调用Thread.sleep()与*中断状态*设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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