并行处理任务并等待完成。CountDownLatch 使用给定计数进行初始化。由于调用 countDown 方法,await 方法将阻塞,直到当前计数达到零,之后将释放所有等待的线程,并且 await 的任何后续调用都会立即返回。
public class ParallelTaskProcessor {
public void processTasks(List<Runnable> tasks) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(tasks.size());
ExecutorService executor = Executors.newFixedThreadPool(10);
for (Runnable task : tasks) {
executor.execute(() -> {
try {
task.run();
} finally {
latch.countDown();
}
});
}
latch.await(); // 等待所有任务完成
executor.shutdown();
}
}
Java中,如果你想在内部类中访问外部方法中的局部变量,那么这些变量必须声明为final。
在Java中,final关键字有几种不同的用途: