Java Multithreading — Introduction
Modern applications need to do many things at once — handle thousands of web requests, process data in the background, keep the UI responsive, and communicate with external services. Multithreading is how Java makes this possible.
In this chapter, you’ll learn what threads are, the difference between concurrency and parallelism, and why multithreading is essential for modern Java development.
What is a Thread?
A thread is a lightweight unit of execution within a process. Every Java application starts with at least one thread — the main thread — which executes your main() method.
Process (your Java app)
├── Main thread (runs main())
├── Thread-1 (handles HTTP request)
├── Thread-2 (processes background job)
└── Thread-3 (writes to database)
Each thread has its own:
- Stack (local variables, method call frames)
- Program counter (which instruction it’s executing)
All threads share:
- Heap (objects, instance variables)
- Method area (class data)
Concurrency vs Parallelism
| Concept | Meaning | Analogy |
|---|---|---|
| Concurrency | Managing multiple tasks by switching between them | One chef switching between multiple dishes |
| Parallelism | Executing multiple tasks simultaneously | Multiple chefs each cooking a different dish |
A single-core CPU can achieve concurrency (time-slicing) but not true parallelism. Multi-core CPUs can achieve both.
Why Multithreading Matters
- Responsiveness — keep the UI responsive while doing background work
- Throughput — handle thousands of simultaneous web requests
- Resource utilization — use all CPU cores efficiently
- Asynchronous I/O — don’t block waiting for network/disk operations
Java’s Threading Model
In traditional Java (before Java 21), one Java thread = one OS thread. This means:
- Threads are expensive to create (~1MB stack each)
- You can run thousands, but not millions, of threads
- Java 21 introduced virtual threads (Project Loom) — lightweight threads that can scale to millions
We’ll cover virtual threads in Chapter 11.
What’s Next?
In the next chapter, you’ll learn how to create and start threads using the Thread class and Runnable interface.