sleep()清除中断标记的问题

来源:5-6 抛出异常

大魔王kite

2021-05-28

package cn.java.threadcoreknowledge.stopthread;

public class RightStopThreadInProd implements Runnable {
    @Override
    public void run() {
        while(true && !Thread.currentThread().isInterrupted()) {
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
            Thread.sleep(2000);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

这是照着课程敲的代码,我有两个地方不懂:

我的理解是throwInMethod方法中的sleep方法接收到中断信息后会清除中断标记,那么循环条件中的“!Thread.currentThread().isInterrupted()“有什么用呢? 2:为什么执行该代码后,程序抛出异常后依旧继续执行循环,而不是停止呢?

图片描述

写回答

1回答

悟空

2021-05-28

1. 为了处理这种情况:还没执行到sleep,就被!Thread.currentThread().isInterrupted()判断到了。

2.因为异常被catch住了

1
2
Jai周杰
补充下第二点,并且 "catch" 也清除了通知中断的标记位
2021-06-19
共2条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程