Multithreading and Concurrency

Lesson 18 of 20

Two call stacks, one program — start threads, watch their output interleave, and learn join, sleep and races.

The big picture

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.