Thread Pools & Executors
Creating threads manually is expensive. Thread pools reuse a fixed number of threads for many tasks, improving performance. The Executor framework (java.util.concurrent) provides high-level thread management. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
40 min•By Priygop Team•Last updated: Feb 2026
Thread Pool Example
Example
import java.util.concurrent.*;
import java.util.*;
public class ThreadPoolDemo {
public static void main(String[] args) throws Exception {
// Fixed thread pool — 3 worker threads
ExecutorService pool = Executors.newFixedThreadPool(3);
System.out.println("=== Thread Pool Demo ===");
// Submit 6 tasks (only 3 run at a time)
for (int i = 1; i <= 6; i++) {
final int taskId = i;
pool.submit(() -> {
String thread = Thread.currentThread().getName();
System.out.println("Task " + taskId + " starting on " + thread);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("Task " + taskId + " completed on " + thread);
});
}
// Shut down the pool
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("\nAll tasks completed!");
// Callable + Future: get results from threads
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<Long>> futures = new ArrayList<>();
long[] ranges = {100000, 200000, 300000};
for (long range : ranges) {
final long r = range;
Future<Long> future = executor.submit(() -> {
long sum = 0;
for (long i = 1; i <= r; i++) sum += i;
return sum;
});
futures.add(future);
}
System.out.println("\n=== Computation Results ===");
for (int i = 0; i < futures.size(); i++) {
System.out.println("Sum to " + ranges[i] + ": " + futures.get(i).get());
}
executor.shutdown();
}
}Try It Yourself: Parallel Task Processor
Try It Yourself: Parallel Task ProcessorJava
Java Editor
✓ ValidTab = 2 spaces
Java|46 lines|1598 chars|✓ Valid syntax
UTF-8