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

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

    You could call waitTillDone() on this Runner class:

    Runner runner = Runner.runner(4); // create pool with 4 threads in thread pool
    
    while(...) {
        runner.run(new MyTask()); // here you submit your task
    }
    
    
    runner.waitTillDone(); // and this blocks until all tasks are finished (or failed)
    
    
    runner.shutdown(); // once you done you can shutdown the runner
    

    You can reuse this class and call waitTillDone() as many times as you want to before calling shutdown(), plus your code is extremly simple. Also you don't have to know the number of tasks upfront.

    To use it just add this gradle/maven compile 'com.github.matejtymes:javafixes:1.3.1' dependency to your project.

    More details can be found here:

    https://github.com/MatejTymes/JavaFixes

提交回复
热议问题