In Java, we can use the CountDownLatch class to achieve similar functionality to Go’s WaitGroups. This allows us to wait for multiple threads to finish their execution.
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.
Each worker thread calls latch.countDown() when it’s done, which is equivalent to wg.Done() in the Go version.
The main thread waits for all workers to finish by calling latch.await(), which is similar to wg.Wait() in Go.
We use Java’s built-in Thread class to create and start new threads, which is analogous to using goroutines in Go.
The TimeUnit.SECONDS.sleep(1) call is used to simulate an expensive task, similar to time.Sleep(time.Second) in the Go version.
This approach demonstrates how to coordinate multiple threads in Java, waiting for all of them to complete before proceeding. However, for more complex scenarios, you might want to consider using higher-level concurrency utilities provided by Java’s java.util.concurrent package, such as ExecutorService and Future.