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

与世无争的帅哥 提交于 2019-11-27 07:12:44

问题


as the title.

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();
}

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


回答1:


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

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

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...



来源:https://stackoverflow.com/questions/9901649/after-catching-interruptedexception-why-thread-currentthread-isinterrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!