登录

java - ExecutorService怎样不用shutdown,awaitTermination实现主线程等待所有子线程完成再继续执行

ExecutorService es = Executors.newFixedThreadPool(THREADPOOLSIZE+1);

        while(true){
            long startTime2 = System.currentTimeMillis();
            numIids = getIds(batchId, LIMITSIZE);
            if (numIids == null || numIids.isEmpty()) {
                break;
            }
            int i = 0;
            int batchSize = numIids.size() / THREADPOOLSIZE;
            if (numIids.size() > THREADPOOLSIZE) {
                for (i = 0; i < THREADPOOLSIZE; i++) {
                    List<Long> subList = numIids.subList(i * batchSize, ((i + 1) * batchSize));
                    es.submit(() -> {
                        try {
                            compute(batchId, subList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
            if (i * batchSize < numIids.size()) {
                List<Long> subList = numIids.subList(i * batchSize, numIids.size());
                es.submit(() -> {
                    try {
                        compute(batchId, subList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            我想在这里实现等待上面所有子线程完成所有任务,然后向下执行(不关闭线程池中的线程,让这些线程重复使用)
        }
        es.shutdown();
        awaitTerminationQuietly(es);
        }
# Java
黄舟黄舟2189 天前615 次浏览

全部回复(2) 我要回复

  • PHPzhong

    PHPzhong2017-04-17 17:52:40

    可以使用 java.util.concurrent.CountDownLatch 这个类

    回复
    0
  • 阿神

    阿神2017-04-17 17:52:40

    看看invokeAll这个方法

    回复
    0
  • 取消回复发送