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

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

    There is a method in executor getActiveCount() - that gives the count of active threads.

    After spanning the thread, we can check if the activeCount() value is 0. Once the value is zero, it is meant that there are no active threads currently running which means task is finished:

    while (true) {
        if (executor.getActiveCount() == 0) {
        //ur own piece of code
        break;
        }
    }
    

提交回复
热议问题