
本文旨在解决使用Executorservice时如何在加班或其他特定情况下停止正在运行的线程,避免完全关闭Executorservice,以便后续任务仍能提交。我们将讨论使用shutdownnow()方法与thread相结合.interrupted()正确的标志方式,以及如何优雅地处理Runnable任务中的中断请求。
在使用Executorservice处理并发任务时,有时需要在特定条件下停止正在执行的任务(如加班)。不建议直接粗略地终止线程,因为它可能会导致资源泄漏或数据不一致。更优雅的方法是要求线程停止,并让线程本身处理停止逻辑。
使用 shutdownNow() 请求停止线程ExecutorService 提供了 shutdownNow() 该方法试图停止所有正在执行的任务,暂停正在等待的任务,并返回等待执行的任务列表。重要的是,shutdownNow() 它不会立即杀死线程,而是设置每个线程 interrupted 标志。
ExecutorService executor = Executors.newFixedThreadPool(10);
List<List<Object>> objectGroup = Lists.partition(objectList, 5);
for (List<Object> eachGroup : objectGroup ) {
CountDownLatch latch = new CountDownLatch(eachGroup.size());
for (Object obj: eachGroup) {
executor.submit(() -> {
try {
doTask(obj);
} catch (InterruptedException e) {
// 处理中断异常,例如,清理资源
System.out.println("Task interrupted!");
} finally {
latch.countDown();
}
});
}
try {
if (!");
} finally {
latch.countDown();
}
});
}
try {
if (!latch.await(15, TimeUnit.MINUTES)) {
// 超时请求停止所有线程
List<Runnable> droppedTasks = executor.shutdownNow();
System.out.println("Timeout! Tasks interrupted: " + droppedTasks.size());
}
}
catch (InterruptedException e) {
System.out.println("Interrupted while waiting for latch!");
executor.shutdownNow();
}
}
// 不要忘记在所有任务完成后关闭它 ExecutorService
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("Executor did not terminate in 60 seconds");
executor.shutdownNow();
}
} catch (InterruptedException ex) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}在 Runnable 检查任务中的中断状态
为了使线程响应中断请求,需要在 Runnable 定期检查任务 Thread.interrupted() 标志。如果这个标志是 true,然后应执行清理操作并退出任务。
public void doTask(Object obj) throws InterruptedException {
while (!Thread.interrupted()) {
// 执行任务的一部分
// ...
// 模拟耗时操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// 重新设置中断标志,为了在方法栈的更高层也能感知到中断
Thread.currentThread().interrupt();
throw e; // 抛出 InterruptedException
}
}
// 实施清理操作,如释放资源
System.out.println("Task is stopping gracefully.");
}
注意事项:
- Thread.interrupted() 该方法将清除当前线程的中断状态。如果需要在方法栈的更高层继续响应中断,则需要捕获 InterruptedException 重新设置中断标志后 Thread.currentThread().interrupt()。
- executor.shutdownNow() 它将返回List,包括尚未执行的任务。您可以根据需要处理这些丢弃的任务。
- 所有任务完成后,一定要调用 executor.shutdown() 来关闭 ExecutorService,并使用 awaitTermination() 等待所有线程完成的方法。如果超时,可以再次调用 executor.shutdownNow()。
- shutdownNow() 以后不能再提交新任务,如果需要继续提交任务,则不应调用此方法。
结合使用 shutdownNow() 方法和在 Runnable 任务中检查 Thread.interrupted() 标志可以优雅地停止 ExecutorService 中线程的目的。 该方法避免了强制终止线程可能出现的问题,并允许线程本身负责清理资源和退出。 请记住,良好的错误处理和资源管理在处理并发编程时至关重要。
以上是如何优雅地停止ExecutorService中线程的详细内容,请关注图灵教育的其他相关文章!