sleep的清除标记位

来源:5-7 恢复中断

慕楠枫桥

2023-05-27

public class StopThread implements Runnable{
@Override
public void run() {

    while (!Thread.currentThread().isInterrupted()) {
        try {
            tsl();
            System.out.println("tsl");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private void tsl() throws InterruptedException{
    Thread.sleep(1000);
}

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new StopThread());//创建
    thread.start();//启动
    Thread.sleep(2000);//主线程睡一秒钟,在执行下面的代码
    thread.interrupt();//中断也没用,要被中断的线程配合才行

}

}
//可以正常响应中断 标记位并没有被清除
底层的tsl()方法我选择向上层抛出异常,由调用方去处理,因为上层调用时run方法,只能自己捕获,不能在方法签名中声明抛出,然而sleep方法不是会清除标记位吗,我也没有catch块中恢复,为啥可以正常响应中断了,还是在run方法中catch会自动把中断信号给恢复?

public class StopThread implements Runnable{
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
tsl();
System.out.println(“tsl”);
}
}

private void tsl() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new StopThread());//创建
    thread.start();//启动
    Thread.sleep(2000);//主线程睡一秒钟,在执行下面的代码
    thread.interrupt();//中断也没用,要被中断的线程配合才行

}

}
//老师这个我可以理解,因为我屏蔽了中断,既没有在方法上抛出也没有在catch块中恢复中断(sleep方法清除了标记位),所以while条件一直为真,死循环-

写回答

1回答

悟空

2023-05-28

主线程休眠时间太长了,子线程已经执行完了。可以改一下试一下。sleep会清除中断标记。

0
0

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

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

2512 学习 · 939 问题

查看课程