Our example demonstrates how to wait for multiple threads to finish using a CountDownLatch. This is similar to the concept of WaitGroups in other languages.
To run the program, save it as waitgroups.groovy and use the groovy command:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Groovy example, we’ve used a CountDownLatch to replicate the functionality of a WaitGroup. The CountDownLatch is initialized with the number of workers, and each worker calls countDown() when it’s finished. The main thread waits for all workers to finish by calling await() on the latch.
We’ve also used a FixedThreadPool to manage our threads, which is a common practice in Java/Groovy for handling multiple concurrent tasks.
Remember that while this example demonstrates basic concurrency, Groovy and Java offer more advanced concurrency utilities for complex scenarios.