public static void main(String[] args) throws Exception {
Thread test = new Thread(() -> {
try {
System.out.println("stateName4:" + Thread.currentThread().getState().name()); // RUNNABLE
int count = 0;
while (true) {
// if (count++ > 10000) {
// System.out.println("success to 10000");
// break;
// }
Thread.sleep(10000);
}
} catch (Exception e) {
if (e instanceof InterruptedException) {
// false 当线程调用sleep(),wait(),join()等方法而阻塞,在被打断时会抛出InterruptedException异常,而且打断状态被重置reset
System.out.println("state1: " + Thread.currentThread().isInterrupted());线程
// Just to set the interrupt flag (set true)
Thread.currentThread().interrupt();
System.out.println("state2: " + Thread.currentThread().isInterrupted()); // trueget
// return thread interrupt status and then clearInterrupt (set false)
System.out.println("state3: " + Thread.interrupted());
System.out.println("state4: " + Thread.currentThread().isInterrupted()); // falseit
System.out.println("stateName5:" + Thread.currentThread().getState().name()); // RUNNABLE
}
} finally {
System.out.println(Thread.currentThread().getName() + "" + (Thread.currentThread().isInterrupted() ? " is interrupted!" : " is not interrupted!"));
System.out.println("stateName6:" + Thread.currentThread().getState().name()); // RUNNABLE
}
});io
// 启动线程
test.start();
System.out.println("stateName1:" + test.getState().name()); // RUNNABLEthread
// 主线程让出cpu
Thread.sleep(1000);
System.out.println("stateName2:" + test.getState().name()); // TIMED_WAITINGtest
// 打断线程
test.interrupt();
System.out.println(test.isInterrupted()); // true方法
Thread.sleep(1000);
System.out.println("stateName3:" + test.getState().name()); // TERMINATED
}cpu