Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to tell all subthreads are done

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");
like image 255
Artemio Ramirez Avatar asked Mar 09 '26 05:03

Artemio Ramirez


1 Answers

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.

like image 122
Peter Lawrey Avatar answered Mar 11 '26 17:03

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!