ExecutorService, how to wait for all tasks to finish

前端 未结 15 2287
攒了一身酷
攒了一身酷 2020-11-22 15:45

What is the simplest way to to wait for all tasks of ExecutorService to finish? My task is primarily computational, so I just want to run a large number of jobs

15条回答
  •  广开言路
    2020-11-22 16:43

    how about this?

    Object lock = new Object();
    CountDownLatch cdl = new CountDownLatch(threadNum);
    for (int i = 0; i < threadNum; i++) {
        executorService.execute(() -> {
    
            synchronized (lock) {
                cdl.countDown();
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }
    cdl.await();
    synchronized (lock) {
        lock.notifyAll();
    }
    

    if you do not add new tasks to ExecutorService , this may wait for all current tasks completed

提交回复
热议问题