
在Java中,线程的停止不是强制性的,而是通过“合作”机制实现的。当要求中断线程时(例如,通过调用Thread).interrupt()方法)它不会立即停止执行。相反,Java虚拟机只设置了该线程的“中断标志”(interrupted status)。线程需要定期检查标志,并根据其状态决定是否终止当前操作、清理资源和退出。
有两种常用的方法可以检查线程中断标志:
- Thread.currentThread().isInterrupted(): 检查当前线程的中断状态,不清除中断标志。
- Thread.interrupted(): 检查当前线程的中断状态,并清除中断标志(重置为false)。
另外,当线程执行某些阻塞操作时(如Thread).sleep(), Object.wait(), BlockingQueue.take()等)中断时,这些操作将抛出InteruptedException。捕获此异常是处理中断请求的另一种重要方法。
ExecutorService与任务中断:shutdownNow()的权衡Executorservice是Java并发包中管理线程池的核心接口。当需要停止Executorservice中的所有任务时,通常会考虑使用shutdownnow()。
executor.shutdownNow()方法的作用如下:
- 试着取消所有正在执行的任务:它将覆盖线程池中所有正在运行的线程,并调用其interupt()设置中断标志。
- 停止等待队列中的任务:任何尚未执行的任务都将立即被删除,并作为列表返回。
- 防止提交新任务:一旦调用shutdownnow(),executorservice将进入“关闭”状态,后续提交的任务将被拒绝。
然而,shutdownNow()副作用是完全关闭ExecutorService,使其无法接受新任务提交。 这与用户提出的“我不想关闭executor(我不能再提交线程)”的需求背道而驰。如果业务场景需要executorservice在处理完当前任务后继续处理后续任务批次,那么shutdownnow()并不是一个合适的解决方案。
取消选择性任务:使用Future接口为了在不关闭整个ExecutorService的前提下选择性地中断或取消特定任务,我们需要使用ExecutorService.submit()方法返回的Future对象。
当你通过executor时.submit(Runnable task)或executor.submit(Callable
Future.cancel(boolean mayInterruptIfRunning)方法:
- 假如任务还没有开始,它将永远不会运行。
- 假如任务已经开始,但尚未完成:
- 当mayinteruptifrunning参数为true时,它将试图中断执行任务的线程。这与直接调用thread有关.interrupt()效果相似。
- 当mayinteruptifrunning参数为false时,它不会中断线程,任务将继续运行直到完成,但future的状态将被标记为已取消,后续调用get()将抛出cancelationexception。
因此,为了在加班后取消特定任务组的需求,我们应该在Countdownlatch加班时间,通过该组任务对应的Future对象,并调用cancel(true)。
实战示例:CountDownlatch超时取消任务以下是基于用户原始代码的改进版本,演示了如何在Countdownlatch超时后取消该批中未完成的任务,同时保持Executorservice的可用性:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ExecutorServiceTaskCancellation {
// 模拟执行耗时任务的方法
private static void doTask(Object obj) {
try {
System.out.println(Thread.currentThread().getName() + " - 开始处理: " + obj);
// 执行模拟任务,并定期检查中断状态
for (int i = 0; i < 10; i++) {
if (Thread.interrupted()) { // 检查中断标志
System.out.println(Thread.currentThread().getName() + " - 任务 " + obj + " 中断,提前退出。");
return; // 响应中断,退出任务
}
Thread.sleep(500); // 模拟耗时操作
}
System.out.println(Thread.currentThread().getName() + " - 完成处理: " + obj);
} catch (InterruptedException e) {
// 捕获InteruptedException,也意味着中断
System.out.println(Thread.currentThread().getName() + " - 任务 " + obj + " 捕获InteruptedException,提前退出。");
// 重新设置中断标志,因为捕获InteruptedException将删除中断标志
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
// 创建固定尺寸的线程池,例如5个线程
ExecutorService executor = Executors.newFixedThreadPool(5);
// 模拟大对象列表
List<String> objectList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
objectList.add("Task-" + (i + 1));
}
// 将对象列表分成每组5个
// 假设在这里使用GuavaListsts.partition,请在实际项目中介绍Guava库
// 或者自己实现分区逻辑
List<List<String>> objectGroups = partitionList(objectList, 5);
int groupCount = 0;
for (List<String> eachGroup : objectGroups) {
groupCount++;
System.out.println("\n--- 开始处理第 " + groupCount + " 组任务 ---");
CountDownLatch latch = new CountDownLatch(eachGroup.size());
List<Future<?>> futures = new ArrayList<>(); // 存储当前组的所有Future对象
for (String obj : eachGroup) {
Future<?> future = executor.submit(() -> {
try {
doTask(obj);
} finally {
latch.countDown(); // 无论任务成功、失败或中断,都减少计数
}
});
futures.add(future); // 将Future添加到列表中
}
try {
// 等待当前的小组任务完成,最长等待15分钟
if (!latch.await(15, TimeUnit.SECONDS)) { // 将15分钟改为15秒方便测试
System.out.println("警告:第 " + groupCount + " 小组任务未能在15秒内完成,试图取消未完成的任务。latch.await(15, TimeUnit.SECONDS)) { // 将15分钟改为15秒方便测试
System.out.println("警告:第 " + groupCount + " 小组任务未能在15秒内完成,试图取消未完成的任务。");
// 试图取消所有未完成的任务
for (Future<?> future : futures) {
if (!future.isDone()) { // 检查任务是否已完成
boolean cancelled = future.cancel(true); // 试着中断任务
System.out.println(" - 尽量取消任务: " + (cancelled ? "成功" : "失败或已完成") + " for " + future);
}
}
} else {
System.out.println("第 " + groupCount + " 小组任务全部完成。");
}
} catch (InterruptedException e) {
System.out.println("等待第 " + groupCount + " 小组任务中断: " + e.getMessage());
Thread.currentThread().interrupt(); // 重新设置中断标志
}
}
// 处理完所有组后,优雅地关闭ExecutorService
System.out.println("处理完所有任务组后,准备关闭ExecutorService。");
executor.shutdown(); // 阻止提交新任务,等待提交任务完成
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("ExecutorService未能及时关闭,试图强制关闭。");
executor.shutdownNow(); // 强制关闭
}
} catch (InterruptedException e) {
System.err.println("关闭ExecutorService时被中断: " + e.getMessage());
executor.shutdownNow(); // 当捕获中断异常时,也被迫关闭
Thread.currentThread().interrupt();
}
System.out.println("ExecutorService已经关闭。");
}
// 模拟Lists.Guava库tition方法可用于实际项目
private static <T> List<List<T>> partitionList(List<T> list, int size) {
List<List<T>> partitions = new ArrayList<>();
if (list == null || list.isEmpty() || size <= 0) {
return partitions;
}
for (int i = 0; i < list.size(); i += size) {
partitions.add(new ArrayList<>(list.subList(i, Math.min(i + size, list.size())));
}
return partitions;
}
}编写可中断的任务
上述示例的关键在于dotask对中断的内部响应。可中断的任务应该是:
- 定期检查中断标志: 在长期运行的循环或计算中,定期调用Thread.interrupted()或Thread.currentThread().isInterrupted()检查是否收到中断请求。
- Interuptedexception处理: 当任务执行阻塞操作时,如果中断,InteruptedException将被抛出。捕获此异常并进行相应的清理和退出操作。
- 重新设置中断标志: 在捕获Interuptedexception后,JVM将清除当前线程的中断标志。如果任务只处理异常,并希望继续向上层传输中断信号,或者当前线程在执行当前任务后需要执行其他任务,则通常需要调用Thread.currentThread().interrupt()重新设置中断标志。
在dotask示例中,我们展示了这两种处理方法:通过threadad.interrupted()在循环中检查,并通过try-catch InteruptedException处理堵塞操作。
注意事项和最佳实践- 中断是合作,不是强制性的: Future.cancel(true)只发送中断信号。任务本身必须设计成响应中断。如果任务代码不检查中断状态或处理InteruptedException,即使调用cancel(true),在自然结束之前,任务也可能继续运行。
- 资源清理: 当任务因中断而提前退出时,确保所有打开的资源(如文件句柄、网络连接等)能够妥善关闭和清理,以避免资源泄露。这通常在finally块中完成。
-
shutdown() vs shutdownNow():
- shutdown():平稳关闭。不再接受新任务,而是等待已提交的所有任务(包括队列中的和正在执行的)完成。
- shutdownNow():立即关闭。试图中断所有正在执行的任务,清空等待队列,并返回未执行的任务列表。
- 在主程序结束时,通常建议先调用shutdown(),然后使用awaittermination()等待一段时间。如果超时仍未关闭,请调用shutdownnow()强制关闭,以确保资源的释放。
- 粒度控制: ExecutorService本身并不直接提供这些功能,如果需要更细粒度的任务管理(例如暂停/恢复任务)。可能需要使用更先进的并发工具,如Semaphore、实现Cyclicbarier或自定义线程池。
- 异常处理: 在任务内部,除处理中断外,还应妥善处理其他运行中的异常,以避免因未捕获的异常而导致线程池中的线程意外终止。
停止任务是Executorservice中常见的需求,但了解其背后的Java线程中断机制非常重要。虽然直接使用shutdownnow()可以中断所有任务,但它将使executorservice无法重用。在需要时,通过存储future对象并调用future.cancel(true),我们可以选择性地中断特定任务,并保持Executorservice的活动。最重要的是,任务代码本身必须是“中断友好”,即主动检查中断状态并响应中断信号,这是取消优雅任务的基石。
以上是ExecutorService中可控任务中断和取消的详细内容。请关注图灵教育的其他相关文章!