Our example demonstrates how to wait for multiple threads to finish using Java’s CountDownLatch. This is similar to the concept of WaitGroups in other languages.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Java example, we use a CountDownLatch instead of a WaitGroup. The CountDownLatch serves a similar purpose, allowing us to wait for a set of operations to complete.
We also use an ExecutorService to manage our thread pool, which is a more idiomatic way to handle concurrent tasks in Java. Each worker is submitted as a task to the executor.
The worker method is now a static method that takes a CountDownLatch as a parameter. It calls countDown() on the latch when it’s done, which is equivalent to calling Done() on a WaitGroup.
In the main method, we initialize the CountDownLatch with a count of 5, create an ExecutorService, and then submit 5 worker tasks. We then call await() on the latch, which blocks until all workers have completed.
Finally, we shut down the ExecutorService. This is an important step in Java to properly clean up thread resources.
Note that Java’s concurrency utilities offer more advanced features for handling exceptions and results from concurrent tasks, such as CompletableFuture or the ExecutorCompletionService.