How to wait for all threads to finish, using ExecutorService?

前端 未结 26 2427
你的背包
你的背包 2020-11-22 01:55

I need to execute some amount of tasks 4 at a time, something like this:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    tas         


        
26条回答
  •  孤独总比滥情好
    2020-11-22 02:29

    
    ExecutorService WORKER_THREAD_POOL 
      = Executors.newFixedThreadPool(10);
    CountDownLatch latch = new CountDownLatch(2);
    for (int i = 0; i < 2; i++) {
        WORKER_THREAD_POOL.submit(() -> {
            try {
                // doSomething();
                latch.countDown();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }
    
    // wait for the latch to be decremented by the two remaining threads
    latch.await();
    

    If doSomething() throw some other exceptions, the latch.countDown() seems will not execute, so what should I do?

提交回复
热议问题