🧠 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

FeatureProcessThread
🧠 MemoryHas its own memory spaceShares memory with other threads in the same process
📦 OverheadHeavy (OS allocates new memory, PCB)Lightweight (uses shared data structures)
🚀 SwitchingSlower (more context to save/restore)Faster (less state to manage)
🔌 IsolationProcesses are isolatedThreads are tightly coupled
🔧 Use CaseRun separate appsRun 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

SystemUse of Threads
Web serverOne thread per request (Apache, Nginx)
Game enginesSeparate threads for rendering, physics, AI
Android appsMain thread (UI), background threads (network, DB)
IDEsUI thread + background compiler thread

⚠️ Multithreading Challenges

ChallengeWhy it’s Hard
🔄 Race ConditionsMultiple threads access same data → inconsistency
🔒 DeadlocksTwo threads wait for each other’s resources
🛠️ Synchronization OverheadLocks/mutexes slow things down
🧪 DebuggingTiming issues make bugs hard to reproduce

🔧 Threading Models

ModelDescription
User-Level ThreadsManaged by user-level libraries (e.g., green threads)
Kernel-Level ThreadsManaged directly by OS (e.g., POSIX threads)
HybridCombines 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.