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

前端 未结 26 2004
你的背包
你的背包 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:46

    You could use this code:

    public class MyTask implements Runnable {
    
        private CountDownLatch countDownLatch;
    
        public MyTask(CountDownLatch countDownLatch {
             this.countDownLatch = countDownLatch;
        }
    
        @Override
        public void run() {
             try {
                 //Do somethings
                 //
                 this.countDownLatch.countDown();//important
             } catch (InterruptedException ex) {
                  Thread.currentThread().interrupt();
             }
         }
    }
    
    CountDownLatch countDownLatch = new CountDownLatch(NUMBER_OF_TASKS);
    ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
    for (int i = 0; i < NUMBER_OF_TASKS; i++){
         taskExecutor.execute(new MyTask(countDownLatch));
    }
    countDownLatch.await();
    System.out.println("Finish tasks");
    

提交回复
热议问题