Threads
1. What Is a Thread? (beginner)
Thread = mini-program inside program (own stack, shared Heap!). Main + workers run together (music + download + chat!). Process = house; threads = family sharing kitchen (Heap!) with own rooms (stacks!).
2. Why Threads? (exam reasons!)
Responsive UI (button works while file loads!), faster multi-core (4 cores → 4× work!), background tasks (music while typing!).
3. First Thread (two ways — exam both!)
// WAY 1: extends Thread (simple, one-shot!)
class Hi extends Thread {
public void run() { for (int i = 0; i < 3; i++) System.out.println("hi " + i); }
}
// WAY 2: implements Runnable (flexible — preferred! can still extend!)
class Hello implements Runnable {
public void run() { for (int i = 0; i < 3; i++) System.out.println("hello " + i); }
}
new Hi().start(); // start() (NOT run()!) → new thread!
new Thread(new Hello()).start(); // wrap Runnable!
// Output interleaves! (hi/hello mixed — schedular decides order!)
4. start() vs run() (THE trap!)
start() = new thread (parallel!). run() = normal call (same thread, NO parallel!). Beginners calling run() get sequential (no magic!).
5. Exam Points
- Define + two ways program — 7 marks, very frequent.
startvsrun— 5 marks, all-time favourite trap.