Java ExecutorService: awaitTermination of all recursively created tasks

后端 未结 11 2116
太阳男子
太阳男子 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 03:50

    You could create your own thread pool which extends ThreadPoolExecutor. You want to know when a task has been submitted and when it completes.

    public class MyThreadPoolExecutor extends ThreadPoolExecutor {
        private int counter = 0;
    
        public MyThreadPoolExecutor() {
            super(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue());
        }
    
        @Override
        public synchronized void execute(Runnable command) {
            counter++;
            super.execute(command);
        }
    
        @Override
        protected synchronized void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            counter--;
            notifyAll();
        }
    
        public synchronized void waitForExecuted() throws InterruptedException {
            while (counter == 0)
                wait();
        }
    }
    

提交回复
热议问题