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
Thanks to @Adam Siemion suggestions, here is a final code:
ExecutorService service = Executors.newFixedThreadPool(cpuCoresNum);
int itNum = 1;
for (int i = 0; i < cpuCoresNum; i++) {
int treadID = itNum++;
service.submit(() -> {
Thread.currentThread().setName("Thread_#" + treadID);
try {
foo();
} catch (Exception e) {
e.printStackTrace();
}
});
}
// wait until all threads will be finished
service.shutdown();
try {
service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}