Java的中断机制没有抢占式机制,只有协作式机制。为何要用中断,线程处于阻塞(如调用了java的sleep,wait等等方法时)的时候,是不会理会我们自己设置的取消标志位的,但是这些阻塞方法都会检查线程的中断标志位。
interrupt | isInterrupted | interrupted |
---|---|---|
将中断标识位设置为true | 读取中断标识,为true则代表要中断当前线程 | 读取中断标识并重新设置为false |
public static void main(String args[]) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
if (Thread.currentThread().isInterrupted()) {//读取中断标识,为true则代表应该中断当前线程
System.out.println("线程中断了11");
//break;
}
boolean isInterrupted = Thread.interrupted();//读取中断标识并清除
//System.out.println("isInterrupted:"+isInterrupted);
try {
Thread.sleep(1000);
System.out.println("打印:" + i);
} catch (InterruptedException e) {//抛异常后将中断标识重新设置为false
System.out.println("线程中断了");
}
}
System.out.println("线程结束");
});
thread.start();
try {
Thread.sleep(3000);
thread.interrupt();//将中断标识位设置为true
} catch (InterruptedException e) {
e.printStackTrace();
}
}
【参考资料】
Java 理论与实践: 处理 InterruptedException
详细分析Java中断机制