In Java, we can use the CountDownLatch class to achieve similar functionality to Go’s WaitGroup. This allows us to wait for multiple threads to finish.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Java version:
We use CountDownLatch instead of WaitGroup. The CountDownLatch is initialized with the number of workers we expect.
Instead of goroutines, we use Java’s ExecutorService to manage a pool of threads.
The worker method takes a CountDownLatch as a parameter and calls countDown() when it’s done, similar to wg.Done() in the original example.
We use latch.await() to block until all workers have finished, similar to wg.Wait().
After all workers are done, we properly shutdown the ExecutorService.
This approach demonstrates how to manage concurrent tasks and wait for their completion in Java, providing similar functionality to the original example.