Java - Threads Part 5: Thread Pools and Executors
Thread pools manage multiple threads efficiently, preventing overhead from creating and destroying threads.
Examples and Explanation
Fixed Thread Pool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
executor.submit(() -> System.out.println(Thread.currentThread().getName() + " is running"));
}
executor.shutdown();
}
}
Explanation: Fixed thread pools execute a fixed number of threads concurrently.
Cached Thread Pool
ExecutorService executor = Executors.newCachedThreadPool();
Explanation: A cached pool creates threads as needed and reuses idle threads.
Scheduled Thread Pool
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(() -> System.out.println("Task executed"), 5, TimeUnit.SECONDS);
scheduler.shutdown();
}
}
Explanation: A scheduled thread pool executes tasks after a delay or periodically.
Conclusion
Java Threads are a powerful tool for concurrent programming. From creation to synchronization, communication, and managing multiple threads, understanding these concepts is vital for writing efficient multi-threaded applications. Using thread pools further optimizes resource usage and improves application performance. Mastering Java Threads enables developers to build robust, scalable, and responsive programs.