java - ExecutorService怎样不用shutdown,awaitTermination实现主线程等待所有子线程完成再继续执行
黄舟
黄舟 2017-04-17 17:50:40
0
2
862

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);
        }
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
PHPzhong

You can use the java.util.concurrent.CountDownLatch class

阿神

Look at the invokeAll method

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template