interrupt()、interrupted()、isInterrupted()区别?

1、interrupt() 线程实例方法,通知线程中断

2、Thread.interrupted() 线程静态方法,返回中断标志且清除(恢复)中断标志

3、Thread.currentThread().isInterrupted() 线程实例方法,仅返回中断标志

2 和 3 的区别:相同点:都是判断线程状态即返回线程状态

                         唯一区别:interrupted() 清除中断标志

                                           isInterrupted() 不清除中断标志

public class InterruptThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() +" interrupted flag is " + Thread.currentThread().isInterrupted());

        while (!Thread.currentThread().isInterrupted()) {
            try {
                System.out.println(Thread.currentThread().getName() + " is running .");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // 响应中断,抛出异常后中断位置会被复位,自己中断自己
                Thread.currentThread().interrupt();
                // 注意区别在这里
                System.out.println(Thread.currentThread().getName()
                        +" interrupted flag is " + Thread.currentThread().isInterrupted());
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new InterruptThread());
        t.start();
        TimeUnit.SECONDS.sleep(3);
        t.interrupt();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值