在多线程任务处理中,ExecutorService
提供了强大的功能,但其关闭和任务完成的监控有时会带来挑战。本文将介绍一种相对鲜为人知的方法,利用ThreadPoolExecutor
的terminated()
钩子方法优雅地跟踪线程池的终止状态。
假设您需要处理一批任务,任务数量未知且在某个时间点结束。简单的shutdown()
方法会立即返回,但后台线程仍需处理剩余任务。如何得知所有任务都已完成?
常见的解决方案,例如CountDownLatch
和awaitTermination()
,各有不足:CountDownLatch
需要预知任务数量;awaitTermination()
则是一个阻塞调用,需要设置超时时间,这并不总是理想的。
更好的方法是利用ThreadPoolExecutor
的terminated()
方法。Executors.newFixedThreadPool()
实际上是ThreadPoolExecutor
的一个便捷封装。ThreadPoolExecutor
提供受保护的可重写方法beforeExecute()
、afterExecute()
和terminated()
,分别在任务执行前、后和执行器完全终止后调用。我们可以重写terminated()
方法来获得任务完成的通知。
以下代码演示了如何通过扩展ThreadPoolExecutor
或使用匿名内部类来重写terminated()
方法:
方法一:使用匿名内部类
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()) {
@Override
protected void terminated() {
super.terminated();
System.out.println("ExecutorService is terminated");
}
};
for (int i = 0; i < 5; i++) {
int temp = i;
executorService.submit(() -> task(temp));
}
executorService.shutdown();
System.out.println("ExecutorService is shutdown");
}
private static void task(int temp) {
try {
TimeUnit.SECONDS.sleep(1L);
System.out.println("Task " + temp + " completed");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
方法二:自定义ThreadPoolExecutor
子类
public static void main(String[] args) {
ExecutorService executorService = getThreadPoolExecutor();
for (int i = 0; i < 5; i++) {
int temp = i;
executorService.submit(() -> task(temp));
}
executorService.shutdown();
System.out.println("ExecutorService is shutdown");
}
private static ThreadPoolExecutor getThreadPoolExecutor() {
return new CustomThreadPoolExecutor(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
}
static class CustomThreadPoolExecutor extends ThreadPoolExecutor {
public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected void terminated() {
super.terminated();
System.out.println("ExecutorService is terminated");
}
}
// task方法与方法一相同
这两种方法都会在所有任务完成后打印"ExecutorService is terminated",从而准确地通知我们线程池的终止。 选择哪种方法取决于个人偏好,匿名内部类更简洁,而自定义类更易于复用和维护。 这为处理未知数量任务的场景提供了一种优雅且可靠的解决方案。 您是否还有其他关于Java并发编程的技巧或经验可以分享?欢迎在评论区留言!