Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?

前端 未结 9 1516
傲寒
傲寒 2020-12-31 09:37

My question is strongly related to this one here. As was posted there, I would like the main thread to wait until the work queue is empty and all tasks have finished. The pr

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 09:49

    Why don't you use a counter? For example:

    private AtomicInteger counter = new AtomicInteger(0);
    

    and increment the counter by one just before submitting the task to the queue:

    counter.incrementAndGet();
    

    and decrement it by one at the end of the task:

    counter.decrementAndGet();
    

    and the check would be something like:

    // ...
    while (counter.get() > 0);
    

提交回复
热议问题