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 version:
We use CountDownLatch instead of WaitGroup. It serves a similar purpose of allowing one thread to wait for multiple other 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.
Instead of goroutines, we create and start regular Java threads.
We use latch.await() to wait for all threads to complete, which is equivalent to wg.Wait().
Java’s TimeUnit.SECONDS.sleep(1) is used to simulate the delay, replacing time.Sleep(time.Second).
We use System.out.printf for formatted printing, which is similar to fmt.Printf.
This example demonstrates how to manage concurrency in Java, waiting for multiple threads to complete before proceeding with the main thread’s execution.