import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EmailSender {
public static void main(String[] args) {
String[] emails = {
"alice@example.com", "bob@example.com", "charlie@example.com",
"dave@example.com", "eve@example.com", "frank@example.com",
"grace@example.com", "heidi@example.com", "ivan@example.com",
"judy@example.com"
};
System.out.println("System started...");
// 1. Create a fixed thread pool with 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
for (String email : emails) {
// 2. Submit the task using a lambda expression
executor.submit(() -> {
System.out.println("Sending email to " + email + "...");
try {
// Simulate network delay
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Email sent to " + email + "!");
});
}
// 3. Shut down the executor to reclaim resources
executor.shutdown();
System.out.println("All tasks submitted. Main thread continues...");
}
}