加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在捕获“I??nterruptedException”之后,为什么“Thread.

发布时间:2020-12-15 04:57:15 所属栏目:Java 来源:网络整理
导读:作为标题. 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(
作为标题.

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

在捕获“I??nterruptedException”之后,为什么“Thread.currentThread().isInterrupted()”的值为false?

解决方法

从Javadoc for Thread.sleep(由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.

我认为isInterrupted()的目的是允许您在调用会抛出InterruptedException的内容之前检测线程是否已被中断.如果你遇到了InterruptedException,假设线程被中断是公平的……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读