// Create a fixed thread pool with 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
// Submit tasks to the thread pool
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId +
" executed by " + Thread.currentThread().getName());
});
}
// Shutdown the executor when done
executor.shutdown();
// Create a cached thread pool
ExecutorService executor = Executors.newCachedThreadPool();
// Submit multiple tasks
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId +
" executed by " + Thread.currentThread().getName());
try {
Thread.sleep(100); // Simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// Shutdown the executor
executor.shutdown();
// Create a scheduled thread pool with 3 threads
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(3);
// Schedule a task to run after 2 seconds
scheduler.schedule(() -> {
System.out.println("Delayed task executed");
}, 2, TimeUnit.SECONDS);
// Schedule a task to run every 5 seconds
scheduler.scheduleAtFixedRate(() -> {
System.out.println("Periodic task executed");
}, 0, 5, TimeUnit.SECONDS);