I want to run a few tasks simultaneously so I have a code that looks like this:
for(final Task task : tasks){
(new Thread(){public void run(){
task.run(args);
}}).start();
How can I know when all of the tasks are done (the amount of tasks can vary) so that I can run something only after everything is done?
System.out.println("All tasks are finished");
A shorter version is to use a parallelStream
tasks.parallelStream().forEach(t -> t.run(args));
This will run all the tasks, using all the CPUs you have (if you have enough tasks) and wait for the all to finish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With