Thread.interrupted() 与.isInterrupted()具体分析

Java中,Thread.interrupted()在没有阻塞方法时会清除中断状态,返回值表示中断前的状态。而Thread.currentThread().isInterrupted()检查中断状态但不改变它。当线程在join(),sleep(),或wait()时被中断,interrupted()会抛出InterruptedException并清除中断标志。
摘要由CSDN通过智能技术生成

在没有join sleep wait 方法时 Thread.interrupted()中断,若是true,则会清除(置为false 但是如果是false则不变),后面的访问是false

中断.isInterrupted()不改变中断状态

public class InterruptDemo {
    private static class Mythread implements Runnable{
        @Override
        public void run(){
            int i=0;
            for(i=0;i<5;i++){
                //  System.out.println(Thread.interrupted());
                System.out.println(Thread.currentThread().isInterrupted());
            }
        }
    }

    public static void main(String[] args) {
        Mythread mythread =new Mythread();
        Thread t1=new Thread(mythread);
        t1.start();
        t1.interrupt();

    }
}
//输出
true
true
true
true
true

interrupted()会将原状态清除

public class InterruptDemo {
    private static class Mythread implements Runnable{
        @Override
        public void run(){
            int i=0;
            for(i=0;i<5;i++){
               System.out.println(Thread.interrupted());
                //   System.out.println(Thread.currentThread().isInterrupted());
            }
        }
    }

    public static void main(String[] args) {
        Mythread mythread =new Mythread();
        Thread t1=new Thread(mythread);
        t1.start();
        t1.interrupt();

    }
}

//输出
true
false
false
false
false

在这里插入图片描述
如果有join sleep wait 方法时阻塞时 ,收到中断通知Thread.interrupted()会抛出一个异常interruptedException,当抛出异常后,当前线程的中断会被清除。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值