Java ExecutorService: awaitTermination of all recursively created tasks

后端 未结 11 2134
太阳男子
太阳男子 2020-11-29 03:27

I use an ExecutorService to execute a task. This task can recursively create other tasks which are submitted to the same ExecutorService and those

11条回答
  •  爱一瞬间的悲伤
    2020-11-29 04:04

    You could use a runner that keeps track of running threads:

    Runner runner = Runner.runner(numberOfThreads);
    
    runner.runIn(2, SECONDS, callable);
    runner.run(callable);
    
    
    // blocks until all tasks are finished (or failed)
    runner.waitTillDone();
    
    
    // and reuse it
    runner.runRunnableIn(500, MILLISECONDS, runnable);
    
    
    runner.waitTillDone();
    
    
    // and then just kill it
    runner.shutdownAndAwaitTermination();
    

    to use it you just add a dependency:

    compile 'com.github.matejtymes:javafixes:1.3.0'

提交回复
热议问题