在捕获“I​​nterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false? [英] after catching "InterruptedException", why "Thread.currentThread().isInterrupted()"'s value is false?

查看:433
本文介绍了在捕获“I​​nterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题。

public static void main(String[] args) throws InterruptedException {

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().isInterrupted());   //print false, who reset the interrupt?

            }
        }
    });

    thread.start();
    TimeUnit.SECONDS.sleep(1);
    thread.interrupt();
}

,为什么Thread.currentThread()。isInterrupted( )的值是假的?

after catching "InterruptedException", why "Thread.currentThread().isInterrupted()"'s value is false?

推荐答案

来自Javadoc的 Thread.sleep (由 TimeUnit.sleep 调用):

From the Javadoc for Thread.sleep (called by TimeUnit.sleep):


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

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

我认为的意图是isInterrupted ()允许您检测线程是否在调用 InterruptedException 之前中断。如果你已经抓住了 InterruptedException ,那么假设线程已经被中断......

I think the intention of isInterrupted() is to allow you to detect whether a thread has been interrupted before calling something which would throw InterruptedException. If you've caught InterruptedException, it's fair to assume that the thread has been interrupted...

这篇关于在捕获“I​​nterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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