Java中interrupt() interrupted() isInterrupted()辨析

Java中interrupt() interrupted() isInterrupted()辨析:

  • interrupt()是将线程的中断标记设置为true,但不会停止线程。在中断状态下如果线程处于阻塞状态(即调用了sleep(),wait(),join()方法)就会产生一个InterruptedException,并且由于线程处于阻塞状态,所以该中断标记立即清除为false
  • interrupted()是测试当前线程是否处于中断状态,是返回true,并且调用后会立即将该中断标记清除为false
public static boolean interrupted() {
   return currentThread().isInterrupted(true);//其中本地方法isInterrupted()中参数true表示是否清除状态位
}
private native boolean isInterrupted( boolean ClearInterrupted);
  • isInterrupted()是作用于调用该方法的线程对象所对应的线程(线程对象对应的线程不一定是当前运行的线程),调用后不会清除中断标记
public boolean isInterrupted() {
   return isInterrupted(false);
}

具体实例:

  1. 阻塞过后,中断标记的清除:
public class TestInterrupt {
    public static void main(String[] args) {
        System.out.println("主线程开始。。");
        Thread.currentThread().interrupt();

        try {
            Thread.sleep(1000);//会抛出异常
        } catch (InterruptedException e) {
            System.err.println("sleep方法出现了异常");
        }
      
        //线程阻塞后,中断状态被清除为false
        System.out.println("主线程是否处于中断状态:" + Thread.currentThread().isInterrupted());//false
        System.out.println("主线程结束。。");
    }
}
/*
结果:
主线程开始。。
sleep方法出现了异常
主线程是否处于中断状态:false
主线程结束。。
*/
  1. 使用isInterrupt(),不会清除中断标记:
public class TestIsInterrupt {
    public static void main(String[] args) {
        System.out.println("主线程开始。。");
        Thread.currentThread().interrupt();
        System.out.println("主线程是否处于中断状态:" + Thread.currentThread().isInterrupted());//true
        System.out.println("主线程是否处于中断状态:" + Thread.currentThread().isInterrupted());//true
        System.out.println("主线程结束。。");
    }
}
/*
结果:
主线程开始。。
主线程是否处于中断状态:true
主线程是否处于中断状态:true
主线程结束。。
*/
  1. 使用interrupt(),会清除中断标记:
public class TestInterrupt {
    public static void main(String[] args) {
        System.out.println("主线程开始。。");
        Thread.currentThread().interrupt();
        System.out.println("主线程是否处于中断状态:" + Thread.interrupted());//true
        System.out.println("主线程是否处于中断状态:" + Thread.interrupted());//false
        System.out.println("主线程结束。。");
    }
}
/*
结果:
主线程开始。。
主线程是否处于中断状态:true
主线程是否处于中断状态:false
主线程结束。。
*/
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值