最近在学习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方法。