java多线程中interrupted和isInterrupted区别

1. 说明
主要通过一些使用来区别这两个函数。

2. 区别
1)this.interrupted():测试当前线程是否已经中断。
2)this.isInterrupted():测试线程是否已经中断。

3. 代码演示

  • 先讲interrupt()

如下

 package www.gzhou.thread2;

public class MyThread4 extends Thread {

    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 5000; i++){
            System.out.println("i=" + (i+1));
        }
    }
}

测试代码一:

public class RunTest4 {
    public static void main(String[] args) {

        try {
            MyThread4 thread4 = new MyThread4();
            thread4.start();
            Thread.sleep(1000);
            thread4.interrupt();
            System.out.println("是否停止1? ="+thread4.interrupted());
            System.out.println("是否停止2?  ="+thread4.interrupted());
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

输出情况:
在这里插入图片描述
因为当前线程从未停止,所以当前线程没有中断,输出也就是只有false了。

实测代码二:

public class Runtest5 {
    public static void main(String[] args) {
        Thread.currentThread().interrupt();
        System.out.println("是否停止1? =" + Thread.interrupted());
        System.out.println("是否停止2? =" + Thread.interrupted());
        System.out.println("end!");
    }
}

输出情况:
在这里插入图片描述
由测试的代码输出结果可知,第二个为false。为什么我的代码已经设置Thread.currentThread().interrupt()中断了,第二个不是true呢?原来在我调用interrupted()的时候,中断状态已经被这个方法清除了,所以在第二次调用interrupted()的时候就是false。

  • 讲isInterrupted
public class RunTest6 {
    public static void main(String[] args) {

        try {
            MyThread4 thread = new MyThread4();
            thread.start();
            Thread.sleep(1000);
            thread.interrupt();
            System.out.println("是否停止1 ? ="+thread.isInterrupted());
            System.out.println("是否停止2 ? ="+thread.isInterrupted());
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

输出情况:

是否停止1 ? =true
是否停止2 ? =true

4. 总结
1)this.interrupted():测试当前线程是否已经是中断中断状态,执行后没有进行状态标志清除。
2)this.isInterrupted():测试线程Thread对象是否已经是中断状态,但不清除状态标志。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值