Multithreading is a technique where multiple threads run concurrently within a program to achieve:
- better CPU utilization,
- faster execution,
- responsive applications.
Key Concepts
Concept | Description |
---|---|
Thread | A lightweight unit of execution |
Process | A running instance of a program (can have many threads) |
Main Thread | The default thread in every Java program |
Concurrency | Multiple tasks making progress over time |
Parallelism | Multiple tasks executed at the same time |
Real-World Analogy
Think of threads like chefs in a kitchen.
One chef (main thread) can cook, but more chefs (threads) = faster meals.
Key Benefits
- Simultaneous task execution.
- Resource sharing (memory).
- Improves performance in I/O-heavy or CPU-bound tasks.
- Better user experience (e.g. UI + background work).
Key Challenges
- Race conditions.
- Deadlocks.
- Thread safety.
- Harder debugging.
Comparison
Thread vs Runnable
Aspect | Thread | Runnable |
---|---|---|
Inheritance | Extends Thread class | Implements Runnable interface |
Flexibility | Less (cant extend other classes) | More flexible |
Usage | new MyThread().start() | new Thread(new MyRunnable()).start() |
Tip
Be ready to explain:
- what a thread is and why multithreading matters,
- difference between concurrency vs parallelism,
- why runnable is preferred over extending Thread.
Parent: _Multithreading