判断线程中断不同JDK版本的区别interrupted()

文章探讨了Java中Thread类的interrupted()方法在不同JDK版本间的实现差异。在JDK1.8中,该方法通过native方法判断并可能清除中断状态。而在JDK18中,中断状态的检查和重置过程更加详细,如果中断标识为true,则会显式地重置为false,以防止丢失中断信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习Thread类里面的interrupted()方法,下述代码的执行结果是false,fasle,true,false。

System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());
System.out.println("1");
Thread.currentThread().interrupt();
System.out.println("2");
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());

比较好奇是如何重置中断标识的,这里比较了一下jdk1.8和jdk18之间的区别,发现源码在这部分有很大的不同。

在JDK1.8中,interrupted()方法的源码是这样的,是通过调用native方法进行的判断,具体的做法还得阅读cpp源码。

    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
    private native boolean isInterrupted(boolean ClearInterrupted);

而jdk18中是这样的:

    public static boolean interrupted() {
        Thread t = currentThread();
        boolean interrupted = t.interrupted;
        // We may have been interrupted the moment after we read the field,
        // so only clear the field if we saw that it was set and will return
        // true; otherwise we could lose an interrupt.
        if (interrupted) {
            t.interrupted = false;
            clearInterruptEvent();
        }
        return interrupted;
    }

这里将native做的事情更详细的展示出来了,就是判断当前线程中断标识的状态,如果是true,那么就重置为false,再调用navite方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值