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