🧠 What is Multithreading?
Multithreading is the ability of a single process to have multiple threads of execution, which run concurrently (or in parallel on multi-core CPUs).
A thread is the smallest unit of CPU execution inside a process.
All threads in a process share the same memory space but have independent execution paths.
💡 Analogy:
Think of a web browser (process):
-
One thread renders the UI,
-
Another fetches network data,
-
Another plays audio/video.
All are part of one app, running in parallel or concurrently.
🔍 Thread vs Process
| Feature | Process | Thread |
|---|---|---|
| 🧠 Memory | Has its own memory space | Shares memory with other threads in the same process |
| 📦 Overhead | Heavy (OS allocates new memory, PCB) | Lightweight (uses shared data structures) |
| 🚀 Switching | Slower (more context to save/restore) | Faster (less state to manage) |
| 🔌 Isolation | Processes are isolated | Threads are tightly coupled |
| 🔧 Use Case | Run separate apps | Run parallel tasks within the same app |
⚙️ How Multithreading Works
Shared between all threads:
-
Code
-
Data segment (global variables)
-
Open files
-
Heap (dynamic memory)
Each thread has its own:
-
Stack
-
Registers
-
Program Counter
🧪 Real-World Use Cases
| System | Use of Threads |
|---|---|
| Web server | One thread per request (Apache, Nginx) |
| Game engines | Separate threads for rendering, physics, AI |
| Android apps | Main thread (UI), background threads (network, DB) |
| IDEs | UI thread + background compiler thread |
⚠️ Multithreading Challenges
| Challenge | Why it’s Hard |
|---|---|
| 🔄 Race Conditions | Multiple threads access same data → inconsistency |
| 🔒 Deadlocks | Two threads wait for each other’s resources |
| 🛠️ Synchronization Overhead | Locks/mutexes slow things down |
| 🧪 Debugging | Timing issues make bugs hard to reproduce |
🔧 Threading Models
| Model | Description |
|---|---|
| User-Level Threads | Managed by user-level libraries (e.g., green threads) |
| Kernel-Level Threads | Managed directly by OS (e.g., POSIX threads) |
| Hybrid | Combines both (most modern OSs) |
📜 Code Example (Java)
public class HelloThread extends Thread {
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
HelloThread t1 = new HelloThread();
HelloThread t2 = new HelloThread();
t1.start();
t2.start();
}
}Both t1 and t2 will run in parallel (if multicore) or concurrently (if single-core).
🧠 Interview-Ready Definition:
Multithreading is the execution of multiple threads within a single process, allowing tasks to run concurrently. Threads share the same memory space but operate independently, enabling more efficient CPU use and responsive applications — especially on multi-core systems.