interrupt和interrupted和isInterrupted的区别

interrupt

Code Demo

package org.fool.thread;

public class InterruptTest1 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100000; i++) {
                    System.out.println(Thread.currentThread().getName() + " i = " + i);
                }
            }
        });

        thread.start();

        thread.interrupt();
    }
}

Note:

从运行结果来看,调用interrupt方法并没有停止线程

interrupted

Code Demo

package org.fool.thread;

public class InterruptTest2 {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " i = " + i);

                if (i == 5) {
                    Thread.currentThread().interrupt();

                    System.out.println("interrupted 1: " + Thread.interrupted());

                    System.out.println("interrupted 2: " + Thread.interrupted());
                }
            }
        });

        thread.start();

    }
}

Console Output

Note:

控制台第一次打印的结果是true,第二次为false;Java Doc中给出的解释是:测试当前线程是否已经中断,线程的中断状态由该方法清除。即如果连续两次调用该方法,则第二次调用将返回false(在第一次调用已清除flag后以及第二次调用检查中断状态之前,当前线程再次中断的情况除外)

所以,interrupted()方法具有清除状态flag的功能 

isInterrupted

Code Demo

package org.fool.thread;

public class InterruptTest3 {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " i = " + i);
            }
        });

        thread.start();

        // main thread interrupt
        Thread.currentThread().interrupt();

        System.out.println(thread.getName() + ":" + thread.isInterrupted());
        System.out.println(thread.getName() + ":" + thread.isInterrupted());
        System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
        System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());

        // thread interrupt
        thread.interrupt();

        System.out.println(thread.getName() + ":" + thread.isInterrupted());
        System.out.println(thread.getName() + ":" + thread.isInterrupted());
    }
}

Console Output

Summary

调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真正的停止线程

interrupted()测试当前线程是否已经是中断状态,执行后具有清除中断状态flag的功能

isInterrupted()测试线程Thread对象是否已经是中断状态,但不清除中断状态flag 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值