Nearby lessons

73 of 125

Java - Thread Pools (Executors)

📌 What You Will Learn
  • What a thread is and how it is different from a process
  • Two ways to create a thread: Thread class and Runnable interface
  • The thread life cycle (states)
  • How threads cooperate: synchronized, wait and notify
  • The modern way: Executors, Callable and lambdas

Thread Pools (Executors) is a core concept of the Java language. This lesson explains The Modern Way — Executors and Callable with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Modern Way — Executors and Callable

Updated knowledge: creating threads manually is fine for learning, but real projects use the Executor Framework (Java 5+) to manage a pool of threads, and Callable to get a result back:

Trainer's Note: Lambdas, Executors and Callable together are the professional way to write multithreaded code today. Also keep an eye on virtual threads (Java 21) — they make thousands of lightweight threads possible. But first master the classic concepts in this chapter.
Example01
JCode Cell
1import java.util.concurrent.*;
2 
3class Test {
4 public static void main(String[] args) throws Exception {
5 ExecutorService pool = Executors.newFixedThreadPool(3); // pool of 3 threads
6 
7 Callable<Integer> job = () -> { // returns a value
8 return 40 + 2;
9 };
10 
11 Future<Integer> result = pool.submit(job);
12 System.out.println("Answer: " + result.get()); // 42
13 pool.shutdown();
14 }
15}
Output
Answer: 42
📝 Key Takeaways
  • A thread is a small unit of work; a process is a running program.
  • Create a thread by extending Thread or (better) implementing Runnable.
  • Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
  • Shared data races when many threads change it; synchronized gives a lock.
  • wait/notify let threads talk; they need the lock.
  • Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
  • Real projects use Executors + Callable instead of raw threads.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1