Skip to content
Advertisement

How to wait for a number of threads to complete?

What is a way to simply wait for all threaded process to finish? For example, let’s say I have:

JavaScript

How do I alter this so the main() method pauses at the comment until all threads’ run() methods exit? Thanks!

Advertisement

Answer

You put all threads in an array, start them all, and then have a loop

JavaScript

Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that’s not a problem: when the loop exits, all threads are completed.

Advertisement