Start With the Problem#
StudyBuddy's backend receives 1,000 requests at the same moment during exam week. Many of them ask the AI to generate a quiz, which means waiting ~3 seconds for an external AI API. Handling them one after another would mean the thousandth student waits 50 minutes.
So the server must work on many requests at once — using several threads, and all 8 CPU cores. But the moment several threads touch the same data, things break in ways that single-threaded code never does:
the "total quizzes generated" counter comes out wrong (Operating Systems Ch 8);
a thread sets a "shutting down" flag, and another thread never sees it and keeps running forever;
two students spend the last AI credit at the same time;
two threads each hold one lock and wait for the other's — the server freezes;
a
HashMapshared by threads silently loses data, or crashes.
Java gives you tools for every one of these. This file shows each problem happening for real, then the tool that fixes it.
The Plain Picture#
A kitchen with one cook can make one dish at a time. Hire more cooks and several dishes progress at once — sharing the same kitchen, fridge and counters (Operating Systems Ch 7).
The Real Names#
A
Threadobject represents one thread of execution. Its work is aRunnable— a functional interface with one method,run()— usually written as a lambda (Modern Java Ch 1).start()asks the operating system to run it concurrently.join()waits until it finishes.Every Java program starts with one thread,
main.
Under the Hood#
Thread t = new Thread(
() -> System.out.println("hello from " + Thread.currentThread().getName()),
"worker-1"
);
System.out.println("state before start: " + t.getState()); // state before start: NEW
t.start();
t.join(); // hello from worker-1
System.out.println("state after join: " + t.getState()); // state after join: TERMINATEDstart() vs run() — a classic trick question:
Thread r = new Thread(() ->
System.out.println("run() on " + Thread.currentThread().getName())
);
r.run(); // run() on main ← NO new thread! It's just a normal method callCalling run() directly runs the code on the current thread. Only start() creates a new one.
Thread states (Thread.getState()) — Java's names for the process states in Operating Systems Ch 3:
NEW ──start()──▶ RUNNABLE ◀──────────────────────────────────┐
│ (running, or ready and waiting for a core)│
├── waiting to enter a synchronized block ──▶ BLOCKED ─────┤
├── wait() / join() / park() with no timeout ─▶ WAITING ──┤
├── sleep(ms) / wait(ms) / join(ms) ──────────▶ TIMED_WAITING
└── run() finishes ──▶ TERMINATEDOther basics:
Thread.sleep(ms)pauses the current thread (TIMED_WAITING); it throws the checkedInterruptedException.Interruption is Java's polite "please stop":
t.interrupt()sets a flag and wakes the thread fromsleep/waitwith anInterruptedException. Handle it by finishing up, and restore the flag withThread.currentThread().interrupt()if you can't stop right there. Never silently swallow it.Daemon threads (
t.setDaemon(true)) don't keep the JVM alive; the program can exit while they run. Normal (non-daemon) threads keep it alive until they finish.
Why you rarely write new Thread(...) in real code: creating an OS thread costs memory (a stack of ~1 MB by default — Operating Systems Ch 6)
and time. Real code reuses threads through pools (next chapter).
Check yourself
4 questionsstart() vs run()?
Show answerHide answer
start() creates a new thread that runs run(); calling run() directly just executes it on the current thread.
What's the difference between BLOCKED and WAITING?
Show answerHide answer
BLOCKED = waiting to acquire a monitor lock for synchronized; WAITING = waiting indefinitely for another thread (e.g. wait, join).
What should code do when it catches InterruptedException?
Show answerHide answer
Stop what it's doing cleanly, or restore the interrupt flag with Thread.currentThread().interrupt() — never ignore it.
What is a daemon thread?
Show answerHide answer
A background thread that doesn't prevent the JVM from exiting.