线程的中断

  1. 什么是线程的中断

给线程设置一个中断的状态.用于标记线程是否被中断过.但是并不是随时都会响应中断.

  1. 相关的方法

java.lang.Thread#interrupt

中断目标线程.给目标线程发一个中断信号.线程被打上中断标记

java.lang.Thread#isInterrupted()

判断目标线程是否被中断.不会清除中断标记

java.lang.Thread#interrupted

判断目标线程是否被中断.清除中断标记

  1. 中断实战
public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("running...");
                Thread.yield();
            }
        });
        t.start();
        t.interrupt();
    }

线程不会终止.因为没有响应中断的逻辑.

 public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("running...");
                Thread.yield();
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Java技术栈线程被中断,程序退出。");
                    return;
                }
            }
        });
        t.start();
        t.interrupt();
    }

会被中断.因为响应了中断逻辑.注意一下 :

Throws:
IllegalArgumentException – if the value of millis is negative
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
public static native void sleep(long millis) throws InterruptedException;

java.lang.Thread#sleep

the interrupted status if the current thread is cleared when this exception is thrown

一个线程不应由其他线程中断或者停止.而是应该由线程自己停止.

Thread.interrupt 的作用不是中断线程.而是通知线程被中断.如果线程处于被阻塞状态.例如:sleep,wait.join.那么线程立即退出阻塞状态.并抛出一个interrupted异常.仅此而已.在线程被同步锁阻塞时.调用interrupt无法去检查中断状态或者抛出异常

如果线程处于正常活动状态.那么会将改线程的中断标志设置为true,仅此而已.被设置中断标志的线程将继续正常运行,不受影响.

正如前文所说synchronized不响应中断,reentrantLock响应异常,下篇文章会用代码实践

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值