记录java线程中断理解,Thread.currentThread().interrupt();
一、概述
中断的理解:
1、Java 线程中断,协作式(通过 Thread.interrupt() 触发,需代码显式检查中断状态或调用可中断方法)。
2、操作系统中断线程(如 Linux 的 kill -9 或强制终止线程)。
二、代码中的应用
以下对中断的描述,场景都是java中,线程协作中断。可以理解为:
当使用线程异步执行方法时,假设这个方法运行1天,那你想提前终止这个方法,就可以调用这个线程的interrupt()方法,触发中断通知,也就是告诉这个线程终止任务,注意这里只是发送了一个取消信号,至于是否取消,要看方法是否检查了取消信号,并做了终止方法处理。
用代码来说就是有2个场景:
一,不响应中断(就是你通知你的,我执行我的)
这个main方法是不会跳出的,不会打印 【执行完成】
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread(() -> {
long i = 0L;
while (i >= 0L) {
i++;
i--;
}
latch.countDown();
});
thread.start();
System.out.println("线程启动");
thread.interrupt();
System.out.println("触发线程中断命令");
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("执行完成");
}
输出结果:
在这里插入代码片
二,响应中断(检查到中断通知,跳出任务执行)
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread(() -> {
long i = 0L;
while (i >= 0L) {
i++;
i--;
if (Thread.interrupted()) {
System.out.println("检查到中断,跳出循环");
break;
}
}
latch.countDown();
});
thread.start();
System.out.println("线程启动");
thread.interrupt();
System.out.println("触发线程中断命令");
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("执行完成");
}
输出结果:
在AQS中的应用:
粗略的看一下,提供了2种类型的方法。
不检查中断
检查中断