I have a code where 4 threads run at the same time. I want to wait until all these 4 threads will be finished. And only after that to continue the app flow.
I tried two approaches:
Thread#join(), this approach works as expected. The code, which comes afterjoin()is executed only after all threads are finished.ExecutorService#shutdown(), this technique allows executing code, which comes aftershutdown()even if not all threads are finished.
Code sample:
ExecutorService service = Executors.newFixedThreadPool(cpuCoresNum);
for (int i = 0; i < cpuCoresNum; i++) {
service.submit(() -> {
try {
foo(); // some long execution function
} catch (Exception e) {
e.printStackTrace();
}
});
}
service.shutdown();
System.out.println("We're done! All threads are finished!");
Why don't submit() and shutdown() wait until all threads will be finished and prints «We're done! All threads are finished!» right after call of service.shutdown();?