java中interrupted()和isInterrupted

interrupted():测试当前线程是否已经中断(当前正在执行的线程,是静态方法)。

isInterrupted():测试线程是否已经中断。(对象线程)。

interrupted()方法具有清除状态的功能,isInterrupted()并未清除状态标志。

示例:

public class Run {
    public static void main(String[] args){
            MyThread thread=new MyThread();
            thread.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
            System.out.println("是否停止1?="+MyThread.interrupted());
            System.out.println("是否停止2?="+MyThread.interrupted());
        System.out.println("end!");
    }
}
i=1
i=2
i=3
i=4
i=5
是否停止1?=false
是否停止2?=false
end!

因为打断的是thread线程,而正在执行的是main线程,所以返回false

改成打断主线程就可以了:

public class Run {
    public static void main(String[] args){
            MyThread thread=new MyThread();
            thread.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread.currentThread().interrupt();
            System.out.println("是否停止1?="+MyThread.interrupted());
            System.out.println("是否停止2?="+MyThread.interrupted());
        System.out.println("end!");
    }
}

i=1
i=2
i=3
i=4
i=5
是否停止1?=true
是否停止2?=false
end!

public class Run {
    public static void main(String[] args){
        MyThread thread=new MyThread();
        thread.start();
        thread.interrupt();
        System.out.println("是否停止1 ? ="+thread.isInterrupted());
        System.out.println("是否停止2 ? ="+thread.isInterrupted());
        System.out.println("end!");
    }
}
是否停止1 ? =true
i=1
是否停止2 ? =true
end!
i=2
i=3
i=4
i=5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值