ExecutorService, how to wait for all tasks to finish

前端 未结 15 2105
攒了一身酷
攒了一身酷 2020-11-22 15:45

What is the simplest way to to wait for all tasks of ExecutorService to finish? My task is primarily computational, so I just want to run a large number of jobs

相关标签:
15条回答
  • 2020-11-22 16:51

    Just use

    latch = new CountDownLatch(noThreads)
    

    In each thread

    latch.countDown();
    

    and as barrier

    latch.await();
    
    0 讨论(0)
  • 2020-11-22 16:51

    Submit your tasks into the Runner and then wait calling the method waitTillDone() like this:

    Runner runner = Runner.runner(2);
    
    for (DataTable singleTable : uniquePhrases) {
    
        runner.run(new ComputeDTask(singleTable));
    }
    
    // blocks until all tasks are finished (or failed)
    runner.waitTillDone();
    
    runner.shutdown();
    

    To use it add this gradle/maven dependency: 'com.github.matejtymes:javafixes:1.0'

    For more details look here: https://github.com/MatejTymes/JavaFixes or here: http://matejtymes.blogspot.com/2016/04/executor-that-notifies-you-when-task.html

    0 讨论(0)
  • 2020-11-22 16:52

    If you want to wait for the executor service to finish executing, call shutdown() and then, awaitTermination(units, unitType), e.g. awaitTermination(1, MINUTE). The ExecutorService does not block on it's own monitor, so you can't use wait etc.

    0 讨论(0)
提交回复
热议问题