Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().isInterrupted());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Has Interrupted!");
e.printStackTrace();
}
}
});
t.start();
try {
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
打断 sleep,并没有打断线程。
sleep 的检查无必要:
Thread t = new Thread(() -> {
try {
while (true) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Has Interrupted!");
e.printStackTrace();
}
});
t.start();
try {
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}