Java – wait for all threads to complete before closing executors
•
Java
This is a snippet of my code
ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
while(conditionTrue)
{
ClassImplementingRunnable c = new ClassImplementingRunnable();
executor.submit(c);
}
Now it's done
executor.shutdown();
What I want to achieve here is that I want to wait for all threads in the thread pool to complete execution, and then I want to close the executor
But I don't think this is what happened here The main thread seems to be closing, it just closes everything
Before my thread pool size was 2, I did the following, and it seemed to work
ClassImplementingRunnable c1 = new ClassImplementingRunnable();
executor.submit(c1);
ClassImplementingRunnable c2 = new ClassImplementingRunnable();
executor.submit(c2);
Future f1 = executor.submit(c1);
Future f2 = executor.submit(c2);
while(!f1.done || !f2.done)
{}
executor.submit();
How do I do this for more threads in the thread pool? thank you.
Solution
You usually use the following idioms:
executor.shutdown(); executor.awaitTermination(Integer.MAX_VALUE,TimeUnit.SECONDS);
>Shutdown just says that the executor doesn't accept a new job. > Awaittermination waits until all the tasks that have been submitted complete what they are doing (or until the timeout is reached - this will not happen for integer.max_value - you may want to use a lower value)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
