Waiting for threads to complete in a executor service

后端 未结 2 1758
轮回少年
轮回少年 2021-01-28 04:47

I have initialized a exectuor service with N threads. After the N threads finishes i want to wait for a while and then reuse the executor with new instance of N threads. How do

2条回答
  •  鱼传尺愫
    2021-01-28 04:53

    Just not shut down your executor - reuse it instead. Generate a collection of Callable tasks instead of Runnable and use:

    executor.invokeAll
    

    It will execute all tasks and return as soon as all of them are done. If MrRunnable is not your class or for whatever reason it have to implements Runnable you can simply convert it to Callable like:

    new Callable()
        {
            @Override
            public Void call() throws Exception {
                worker.run();
                return null;
            }
        };
    

提交回复
热议问题