Multithreading and Concurrency
Lesson 18 of 20Two call stacks, one program — start threads, watch their output interleave, and learn join, sleep and races.
Two call stacks at once
A thread is an independent call stack that the JVM runs alongside main. start() sets one loose; run() is the code it carries.
Two ways in
extends Thread, or implement Runnable and hand it to a Thread — Runnable wins when you also need extends.
start(), not run()
start() asks the JVM to run run() on a NEW call stack. Calling run() directly just runs it on yours.
Interleaving
Two threads interleave their prints unpredictably — the exact order can differ every run.
join() = wait here
t.join() makes the caller pause until t finishes — the simplest cure for racing output.
The life of a thread
From birth to termination — with pauses for sleep and join along the way.
One start(), two call stacks
This narration shows one possible order (main prints first, then the worker) — with real threads the order can vary.
1public class ThreadDemo {2public static void main(String[] args) {3Worker w = new Worker();4System.out.println("main: about to start");5w.start();6}7}89class Worker extends Thread {10public void run() {11System.out.println("worker: running");12}13}
Two classes: the demo, and a Worker that extends Thread and overrides run().
Thread vocabulary
Match each term to its meaning.
join() to the rescue
Without join the order would be a coin flip — here it is not.
1public class JoinDemo {2public static void main(String[] args) throws InterruptedException {3Thread t = new Thread(new Job());4t.start();5t.join();6System.out.println("main done");7}8}9class Job implements Runnable {10public void run() {11System.out.println("worker");12}13}
Hint: join() makes main WAIT until t finishes — so the worker line always prints first, every single run.
Key takeaways
A thread is its own call stack running beside main.
start() spawns the stack and runs run() on it; calling run() directly runs nothing new.
Implements Runnable when you want to extend something else too.
Thread output interleaves unpredictably — never assume an order without join().
join() turns "whenever" into "after that thread finishes".