据我所知,对正在阻塞的线程,如 sleep 中的线程,执行 interrupt 方法,会使该线程抛出异常,但是中断标记依旧是 false。我使用如下代码进行了验证:
import static java.lang.Thread.sleep;
public class MainDemo {
public static void main(String[] args) throws InterruptedException{
Thread thread = new Thread(() -> {
try {
sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread.start();
sleep(1000);
System.out.println( "interrupt...");
thread.interrupt();
System.out.println("中断标记:" + thread.isInterrupted());
}
}
执行结果见下图:
想知道这里为什么中断标记是 true,而不是 false,按理来说应该是 false,因为打断阻塞线程,会以抛出异常的方式来执行。