ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.execute(() -> { // task to execute asynchronously }); executorService.shutdown();
ListIn this example, we create a collection of Callable tasks to execute asynchronously. We submit these tasks to the ExecutorService using the invokeAll() method, which waits for all tasks to complete and returns a List of Future objects representing the results of each task. We iterate over the results and print them to the console. This code snippet is also from the java.util.concurrent package.> tasks = Arrays.asList( () -> "Task 1", () -> "Task 2", () -> "Task 3" ); ExecutorService executorService = Executors.newFixedThreadPool(3); try { List > results = executorService.invokeAll(tasks); for (Future result : results) { System.out.println(result.get()); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executorService.shutdown();