java - 多线程情况下调用 interrupt 方法时的一些细节

java多线程情况下调用 interrupt 方法时的一些细节

1. 设置标志位 isIntertupted 时尝试唤醒堵塞状态线程的情况.

public class Demo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // currentThread 获取当前线程的实例
            // Thread.currentThread() <=> thread
            // isInterrupted() 就是一个 thread 的一个标志位
            // isInterrupted() 默认为 false
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Hello thread");
                try {
                    // 在执行interrupt 时 sleep 会被立即唤醒并将标志位改为false
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 将 isInterrupted 标志位设置为 true
        thread.interrupt();
    }
}
  • 按照我们的愿意一下是我们想要的结果
    在这里插入图片描述
  • 但是实际上的运行结果
    在这里插入图片描述
  • 原因
    在这里插入图片描述
  • 如果需要让程序结束那么就应该在catch 里面添加一个break
public class Demo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // currentThread 获取当前线程的实例
            // Thread.currentThread() <=> thread
            // isInterrupted() 就是一个 thread 的一个标志位
            // isInterrupted() 默认为 false
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Hello thread");
                try {
                    // 在执行interrupt 时 sleep 会被立即唤醒并将标志位改为false
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 如果需要结束循环就需要加上一个break
                    break;
                }
            }
        });

        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 将 isInterrupted 标志位设置为 true
        thread.interrupt();
    }
}
  • 结果
    在这里插入图片描述
    [总结]
  • sleep 在执行时会检查 isInterrupted 标志位是否为false 如果不是就会将其置位false
  • interrupt 会将isInterrupted 标志位 设置为ture ,并将处于阻塞的状态下调用该方法的线程唤醒

小提示:

  • 当执行到 interrupt 时恰好线程被自动唤醒时就会不抛异常结束程序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值