public static void main(String[] args) {
// 假设有5个上传任务
int numberOfTasks = 5;
// 初始化CountDownLatch
CountDownLatch latch = new CountDownLatch(numberOfTasks);
// 创建固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(numberOfTasks);
for (int i = 0; i < numberOfTasks; i++) {
// 为每个上传任务创建一个Runnable
Runnable uploadTask = () -> {
try {
// 模拟上传任务
System.out.println("Starting upload task " + Thread.currentThread().getName());
Thread.sleep(((int) (Math.random() * 60) + 1) * 1000);
System.out.println("Completed upload task " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 任务完成后,CountDownLatch的计数减1
latch.countDown();
}
};
// 执行任务
executor.execute(uploadTask);
}
try {
// 等待所有任务完成
latch.await();
System.out.println("All upload tasks are completed.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭线程池
executor.shutdown();
}
}