百万数据用线程池怎么确定结束的时间
在处理百万数据且使用线程池的情况下,确定任务结束时间可以考虑以下几种方法:
使用 CountDownLatch:创建一个 CountDownLatch 对象,其初始值设为线程池要执行的任务数量。每个任务执行完毕后,调用 countDown() 方法将计数减 1 。主线程调用 await() 方法等待,直到计数变为 0,这就表示所有任务都已完成,此时可以记录结束时间。例如:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) throws InterruptedException {
int taskCount = 100; // 假设任务数量
CountDownLatch latch = new CountDownLatch(taskCount);
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < taskCount; i++) {
executor.submit(() -> {
try {
// 模拟任务执行
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
});
}
long startTime = System.currentTimeMillis();
latch.await();
long endTime = System.currentTimeMillis();
System.out.println("所有任务执行完毕,耗时:" + (endTime - startTime) + " 毫秒");
executor.shutdown();
}
}
2.使用 Future 和 FutureTask:提交任务到线程池时会返回 Future 对象,通过 Future 的 isDone() 方法判断任务是否完成。可以将所有 Future 对象收集起来,循环检查它们的状态,当所有 Future 都表示任务已完成时,即为任务结束时间。
3.自定义线程池监控:继承 ThreadPoolExecutor ,重写 afterExecute 方法,在任务执行完成后记录已完成任务数,当已完成任务数达到总任务数时,确定任务结束并记录时间。
788

被折叠的 条评论
为什么被折叠?



