运行中的中断
1. 使用Thread.interrupted()
静态方法调用一次后会清除标志。
// no
System.out.println(Thread.interrupted());
// interrupt
Thread mainThread = Thread.currentThread();
mainThread.interrupt();
// yes and clear
System.out.println(Thread.interrupted());
// no
System.out.println(Thread.interrupted());
2. 使用object.isInterrupted()
实例方法不会清除标志。
// interrupt
Thread mainThread = Thread.currentThread();
// no
System.out.println(mainThread.isInterrupted());
mainThread.interrupt();
// yes and not clear
System.out.println(mainThread.isInterrupted());
// yes
System.out.println(mainThread.isInterrupted());
阻塞时中断
public class BlockedInterrupted {
public static void main(String[] args) {
Thread t = new Thread(BlockedInterrupted::run);
t.start();
// main thread sleeps for 5 seconds
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Interrupt the sleeping thread
t.interrupt();
}
public static void run() {
int counter = 1;
while (true) {
try {
Thread.sleep(1000);
System.out.println("Counter:" + counter++);
}
catch (InterruptedException e) {
System.out.println("I got interrupted!");
return;
}
}
}
}
阻塞时的中断不会改变标志,而是引发一个InterruptedException异常,捕获异常退出即可。