Java:countDownLatch

发布于 2021-06-19  685 次阅读


解释:

我们要读取处理 6 个⽂件,这 6 个任务都是没有执⾏顺序依赖的任务,但是我们需要返回给⽤户
的时候将这⼏个⽂件的处理的结果进⾏统计整理。


为此我们定义了⼀个线程池和 count 为 6 的 CountDownLatch 对象 。使⽤线程池处理读取任务,
每⼀个线程处理完之后就将 count-1,调⽤ CountDownLatch 对象的 await() ⽅法,直到所有⽂件
读取完之后,才会接着执⾏后⾯的逻辑。

public class CountDownLatchExample1 {
    // 处理⽂件的数量
    private static final int threadCount = 6;
    public static void main(String[] args) throws InterruptedException {
        // 创建⼀个具有固定线程数量的线程池对象(推荐使⽤构造⽅法创建)
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadnum = i;
            threadPool.execute(() -> {
                try {
                    //处理⽂件的业务操作
 ......
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //表示⼀个⽂件已经被完成
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        threadPool.shutdown();
        System.out.println("finish");
    }
}


欢迎欢迎~热烈欢迎~