interrupt

interrupt

  • 调用方法是通过指定线程调用**interrupt()**方法
  • interrupt()方法的作用不是打断线程,而是**通知线程此时应该中断**,stop()方法会直接终止线程
  • 如果一个线程处于**被阻塞的状态**(wait、sleep、join)时,调用interrupt()方法后,该线程会**退出阻塞状态**,并且**会**抛出 **InterruptedException** 异常,**不会**存在中断标记。
  • 如果一个线程**没有处于阻塞状态**,则interrupt()方法不会对其造成影响,只会将该线程的**中断标记设置为true**
  • 如果线程是**被阻塞的状态**,但是由**LockSupport.park()**阻塞的,此时调用interrupt()方法后,该线程**会退出阻塞**,但是**不会**抛出 **InterruptedException** 异常,**会**存在中断标记。
public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();

    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();           // Just to set the interrupt flag
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}

isInterrupted

  • 返回该线程当前是否存在中断标记
public boolean isInterrupted() {
    return isInterrupted(false);
}

interrupted

  • 返回当前线程的中断标记,并且会清除线程上的中断标记
  • 如果该线程已经处于中断状态,此时调用两次interrupted()方法
  • 第一次运行会返回**true**,此时会将线程的**中断标记去除**
  • 第二次运行会返回**false**,因为第一次运行时已经将线程的中断标记去除
public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值