Thread-线程中断机制(interrupt)

  • 导语

在线程的中断机制里面有三个比较相似的方法,分别是interrupt()、isInterrupted()、interrupted(),之前一直没有了解的很透彻,记录一下。

Java的中断是一种协作机制。调用线程对象的interrupt方法并不一定就中断了正在运行的线程,它只是要求线程自己在合适的时机中断自己。每个线程都有一个boolean的中断状态(这个状态不在Thread的属性上),interrupt方法仅仅只是将该状态置为true。

方法对比

方法描述
interrupt()中断线程,将会设置该线程的中断状态位,即设置为true
isInterrupted()判断某个线程是否已被发送过中断请求
interrupted()判断某个线程是否已被发送过中断请求,并且将中断状态重新置为false

中断分析

如果一个线程处于了阻塞状态(如线程调用了thread.sleep、thread.wait、I/O操作方法等进入阻塞状态),则在线程检查中断标示时如果发现中断标示为true,则会在这些阻塞方法(sleep、wait、I/O 操作方法)调用处抛出InterruptedException异常,并且在抛出异常后立即将线程的中断标示位清除,即重新设置为false。抛出异常是为了线程从阻塞状态醒过来,并在结束线程前让程序员有足够的时间来处理中断请求。代码示例:

public static void main(String args[]) {
   Thread thread = new Thread(() -> {
       while (!Thread.currentThread().isInterrupted()) {
           try {
               Thread.sleep(1000);
               System.out.println("线程尚未被中断");
           } catch (InterruptedException e) {
               // 线程阻塞被中断后,抛出异常后,会将中断状态还原回去(置为false),在捕获异常后,可以将状态置为true,方便外层判断
               Thread.currentThread().interrupt();
               // 获取中断状态为true
               System.out.println("inner thread..." + Thread.currentThread().isInterrupted());
               e.printStackTrace();
           }
       }
       // 获取中断状态为true
       System.out.println("线程中断..." + Thread.currentThread().isInterrupted());
   });
   // 获取中断状态为false
   System.out.println("start thread..." + thread.isInterrupted());
   thread.start();
   try {
       Thread.sleep(3000);
   } catch (InterruptedException e) {
       e.printStackTrace();
   }
   // 获取中断状态为false
   System.out.println("interrupt thread ..." + thread.isInterrupted());
   // 线程内部调用了sleep阻塞方法,调用interrupt(),抛出InterruptedException异常
   thread.interrupt();
   try {
       Thread.sleep(3000);
   } catch (InterruptedException e) {
       e.printStackTrace();
   }
   // 获取中断状态为false?按照我的理解,线程在内部已经将中断状态置为了true,这里获取的依然为false,需要再研究一下
   System.out.println("end thread..." + thread.isInterrupted());
}

通过以上分析,对线程的中断机制应该有了一个基本的了解。但具体是如何实现中断,跟踪代码可以看到,是调用了native方法,下次再进行分享。

在这里插入图片描述
扫码关注了解更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值