ExecutorService executor = Executors.newFixedThreadPool(24);
for (DropPartition dropPartition : dropPartitions) {
executor.execute(new ThreadCustomDropAll(conn, dropPartition, dropAllLog, dropRunLog, dropPartitionDao));
}
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
dropRunLog.error("================线程池结束=============");
break;
}
try {
dropRunLog.error("================线程池正在运行=============");
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
一种更优雅的写法是使用 CompletionService,它可以帮助你更方便地管理多线程任务的完成情况。
使用 CompletionService 的基本步骤如下:
创建一个 Executor 和一个 CompletionService,并将 Executor 作为参数传给 CompletionService 的构造函数。
将需要执行的任务提交给 CompletionService。
使用 CompletionService 的 take() 方法获取已完成的任务,或者使用 poll() 方法获取并移除已完成的任务。
代码如下:
Executor executor = Executors.newFixedThreadPool(24);
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
for (DropPartition dropPartition : dropPartitions) {
completionService.submit(new ThreadCustomDropAll(conn, dropPartition, dropAllLog, dropRunLog, dropPartitionDao));
}
for (int i = 0; i < dropPartitions.size(); i++) {
Future<String> future = completionService.take();
String result = future.get();
// do something with the result
}
使用 CompletionService 可以让更方便地处理任务的完成情况,而不用像上面的代码那样通过循环来检查线程池是否结束。