Single Tasking Using Threads
1. What It Means (beginner — odd-sounding!)
Single tasking with threads = ONE worker thread + main (sequential handoff!). Used to learn lifecycle: main waits (join) while worker finishes. Like relay: one runs at a time!
2. Code — Main Waits for Worker (join!)
class Bill implements Runnable {
public void run() {
System.out.println("bill: adding items...");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("bill: total=150");
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Bill());
t.start(); // worker starts
t.join(); // MAIN WAITS (single-task feel — ordered!)
System.out.println("main: pay done!"); // prints AFTER bill!
}
// Output order guaranteed: bill lines → pay done! (join forces!)
3. Why? (exam viva!)
Teaches start + join + order control. Real single-tasking needs no threads — this pattern shows coordination (background + wait!).
4. Traps
join()throwsInterruptedException(handle/throws!).- Without
join, main may end first (worker orphan — output jumbled!). join(1000)waits max 1s (timed version!).
5. Exam Points
joinprogram + order guarantee — 5 marks, frequent.- With vs without
joinoutput — 3 marks, trap.