Our example demonstrates how to wait on multiple channel-like operations in Java. We’ll use ExecutorService and Future to simulate concurrent operations.
In this example, we use ExecutorService and Future to simulate channel-like operations. Each task sleeps for a certain amount of time before returning a value, simulating blocking operations executing concurrently.
We use a loop to check which Future is done, simulating the select statement. When a Future is done, we print its result and mark it as processed.
To run the program:
Note that the total execution time is only about 2 seconds since both the 1 and 2 second sleeps execute concurrently.
While Java doesn’t have built-in channels or a select statement like some other languages, we can achieve similar functionality using Java’s concurrency utilities. This example demonstrates how to wait on multiple concurrent operations and process their results as they become available.