Threads run code side by side — spawn them with Thread.new, wait with join, and see why their console output can interleave.
The big picture
Two lines of execution, one program
A thread is a second line of execution inside the same process — it shares your objects and prints to the same console.
1
Thread.new Spawns
Thread.new { ... } starts the block immediately on its own line of execution.
2
join Waits
t.join blocks the caller until that thread has completely finished.
3
Everything Is Shared
Threads see the same objects and globals — shared state needs care.
4
Timing Is Real
Without sleeps or joins, which thread prints first can change from run to run.
Two lines of execution, one program
Thread.new Spawns1Thread.new { ... } starts the block immediately on its own line of execution.
join Waits2t.join blocks the caller until that thread has completely finished.
Everything Is Shared3Threads see the same objects and globals — shared state needs care.
Timing Is Real4Without sleeps or joins, which thread prints first can change from run to run.
4 building blocks make up Two lines of execution, one program
Watch it run
Main and worker take turns
One run of this program: the sleep makes this order reliable — without it, the two prints could swap.
threads.rb
1t = Thread.newdo
2puts"worker: starting"
3sleep(0.1)
4puts"worker: done"
5end
6
7puts"main: working meanwhile"
8t.join
9puts"main: all finished"
main
Thread.new starts the block on a second line of execution; t holds that thread.
Memory
t= #<Thread>
Console
output appears as the program runs…
Step 1/7
Visualize
The life of a thread
A thread is born running, dozes when it waits, and dies when its block ends.
process decision input / output start / end
How it works
A timeline of one run
Press Run to replay the exact interleaving the stepper showed.
Challenge
Predict the output
The worker naps first — main slips in while it sleeps.
nap.rb
1t = Thread.newdo
2sleep(0.05)
3puts"T-done"
4end
5
6puts"main-1"
7t.join
8puts"main-2"
Your predicted output — one line per console line
Hint: The worker sleeps for 50 milliseconds before printing, so main comfortably prints its line during the nap. join then holds main until the worker is finished, and only then prints the last line.
Recap
Key takeaways
Key takeaways5 takeaways
01
Thread.new { } starts a second line of execution immediately.
02
join waits for a thread to finish before the caller moves on.
03
Threads share memory — the same objects, the same globals.
04
sleep yields the interpreter so other threads get their turns.
05
Unjoined threads can be cut off when the main script exits.