Java 学习笔记之 线程interrupted方法

线程interrupted方法:

 

interrupted()是Thread类的方法,用来测试当前线程是否已经中断。

public class InterruptThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i< 5000000; i++){
            System.out.println("i=" + (i + 1));
        }
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testInterruptThread();
    }

    public static void testInterruptThread(){
        try {
            InterruptThread it = new InterruptThread();
            it.start();
            Thread.sleep(1000);
            it.interrupt();
            System.out.println("First call: " + Thread.interrupted());
            System.out.println("Second call: " + Thread.interrupted());
        } catch (InterruptedException e) {
            System.out.println("Main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

运行结果:

从控制台打印的结果来看,返回的结果是false,因为当前线程是main,被中断的却是InterruptThread,所以main线程不受影响。 

再看一个例子:

public class ThreadRunMain {
    public static void main(String[] args) {
        testMainInterruptThread();
    }

    public static void testMainInterruptThread(){
        Thread.currentThread().interrupt();
        System.out.println("First call: " + Thread.interrupted());
        System.out.println("Second call: " + Thread.interrupted());
        System.out.println("end!");
    }
}

运行结果:

同样是调用Thread.interrupted(), 但是为什么第一次结果是true,第二次确是false呢?

因为interrupted()方法具有清除状态功能,所以第二次调用interrupted()返回的值是false。

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7668045.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值