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

前端 未结 9 1432
傲寒
傲寒 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:56

    You could use an atomic counter to count the submit (like has been said, before actually submitting). Combine this with a semaphore and release it in the afterExecute hook that a ThreadPoolExecutor provides. Instead of busy-waiting, call semaphore.acquire( counter.get()) after the first round of jobs has been submitted. But the number of acquires will be too small when calling acquire since the counter may increase later on. You would have to loop the acquire calls, with the increase since the last call as the argument, until the counter does not increase anymore.

提交回复
热议问题