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

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

    Just my two cents. To overcome the requirement of CountDownLatch to know the number of tasks beforehand, you could do it the old fashion way by using a simple Semaphore.

    ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
    int numberOfTasks=0;
    Semaphore s=new Semaphore(0);
    while(...) {
        taskExecutor.execute(new MyTask());
        numberOfTasks++;
    }
    
    try {
        s.aquire(numberOfTasks);
    ...
    

    In your task just call s.release() as you would latch.countDown();

提交回复
热议问题