import java.util.concurrent.*; public class ExecutorServiceExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(3); // create a thread pool of size 3 Callabletask1 = () -> { Thread.sleep(1000); // simulate some computation return "Task 1 completed"; }; Callable task2 = () -> { Thread.sleep(1500); // simulate some computation return "Task 2 completed"; }; Callable task3 = () -> { Thread.sleep(500); // simulate some computation return "Task 3 completed"; }; Callable task4 = () -> { Thread.sleep(2000); // simulate some computation return "Task 4 completed"; }; Callable task5 = () -> { Thread.sleep(300); // simulate some computation return "Task 5 completed"; }; List > tasks = Arrays.asList(task1, task2, task3, task4, task5); List > futures = executor.invokeAll(tasks); futures.stream().map(future -> { try { return future.get(); } catch (Exception e) { throw new IllegalStateException(e); } }).forEach(System.out::println); executor.shutdown(); // shutdown the thread pool } }
import java.util.concurrent.*; public class ExecutorServiceExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); // create a single-threaded executor Runnable task1 = () -> { System.out.println("Task 1 completed"); }; Runnable task2 = () -> { System.out.println("Task 2 completed"); }; Runnable task3 = () -> { System.out.println("Task 3 completed"); }; Listtasks = Arrays.asList(task1, task2, task3); List > futures = executor.invokeAll(tasks); executor.shutdown(); // shutdown the executor } }