Concurrency is one of those topics you can read about for weeks and still not feel. The bugs depend on timing, the output changes every run, and most explanations stay abstract.
So I built a small lab where every concept is a runnable lesson, and every line of output tells you which thread did what, and when. This series walks through it, one lesson per article:
| # | Lesson |
|---|---|
| 1 | Multithreading basics (this article) |
| 2 | Synchronization |
| 3 | ExecutorService |
| 4 | CompletableFuture |
| 5 | Concurrent collections |
| 6 | Virtual threads |
| 7 | Capstone: a coffee shop that uses all of it |
Everything is set in a coffee shop: baristas are threads, the espresso machine is a lock, the order rail is a queue. It sounds silly, but it makes the ideas stick.
Code: github.com/baarayy/advanced-java-section · Java 21, no frameworks.
Running the lab
The Maven wrapper is included, so you only need JDK 21 or newer:
Every line of output looks like this:
Read the thread column first. It tells you whether things really ran in parallel. A small Log helper adds it to every line:
And Work.io(ms) simulates slow I/O (a network call, a database query, brewing a coffee) by sleeping.
What is a thread?
A thread is an independent path of execution inside your program. Every Java program starts with one, called main. When you start more, they run at the same time: truly in parallel on different CPU cores, or taking turns on the same core.
Two facts explain almost everything that follows:
- Each thread has its own call stack. Local variables belong to one thread.
- All threads share the same heap. Objects and fields are visible to every thread.
That sharing is what makes threads useful, and it's also the source of every bug in the next article. For now, let's just make some threads.
1. Three ways to create a thread
Run it a few times and the order of those three lines can change. Nothing guarantees which thread runs first. That's the first rule of concurrency: unless you coordinate threads, you don't control their order.
Prefer option (a) or (b). Passing a Runnable keeps what to do separate from how it runs, which is exactly what lets you hand the same task to a thread pool later (lesson 3) or a virtual thread (lesson 6). The Java 21 builder also has .factory(), which creates threads named barista-1, barista-2, and so on. We'll use that a lot.
2. start() vs run()
The most common beginner bug:
run() is just the method that holds the task. Calling it yourself runs the task on the current thread, synchronously. Only start() asks the JVM for a new thread. The code compiles either way, which is why this bug survives code review.
3. join(): waiting for a thread, and the speed-up
Three orders, each taking 300 ms to brew. First one barista, then three:
903 ms down to 310 ms. Look at the thread column: in the first half everything happens on main, one after another. In the second half, three different threads start within the same millisecond.
join() is what makes the measurement honest. main starts the three baristas, then waits for each to finish. Remove the joinAll call and main reports about 0 ms, because starting a thread returns immediately. The work happens later, without main knowing.
Starting a thread returns immediately. If you need the result, or need to know it's done, you have to wait for it.
4. Thread states
A thread moves through a small set of states, and getState() shows them. That's useful when debugging a stuck app:
| State | Meaning |
|---|---|
NEW | Created, start() not called yet |
RUNNABLE | Running, or ready to run and waiting for a CPU |
BLOCKED | Waiting to enter a synchronized block another thread holds (lesson 2) |
WAITING | Waiting with no time limit, e.g. join() or wait() |
TIMED_WAITING | Waiting with a time limit, e.g. sleep(200) |
TERMINATED | Finished |
When a production app hangs, a thread dump (jstack <pid>) lists every thread with exactly these states. A wall of BLOCKED threads usually means lock contention or a deadlock.
5. Stopping a thread: ask, don't force
You can't safely force a thread to stop. (Thread.stop() exists, but it's deprecated because killing a thread mid-update can leave objects half-written.) Instead, you ask it to stop with interrupt(), and the thread checks for that request and stops cleanly:
An interrupt reaches a thread in one of two ways:
- If the thread is running normally, its interrupt flag is set, and
isInterrupted()returnstrue. - If it's blocked in
sleep(),wait(),join()or similar, that call throwsInterruptedException.
Here's the trap: throwing InterruptedException clears the flag. If the catch block doesn't call Thread.currentThread().interrupt() again, the while loop sees a clean flag and keeps brewing forever. The stop request was swallowed.
This is one of the most common bugs in real Java code:
The rule: when you catch InterruptedException, either rethrow it or restore the flag. The lab's Work.io() helper does exactly that before giving up.
6. Exceptions inside threads
What happens when a thread throws?
An exception kills only the thread that threw it. main keeps going and never finds out. Without a handler, the stack trace is printed to System.err and that's it: no crash, no error returned to anyone.
That's convenient and dangerous at the same time. In lesson 3 we'll see how ExecutorService and Future carry exceptions back to the code that asked for the work.
Common mistakes
- Calling
run()instead ofstart(). It compiles, and nothing runs in parallel. - Swallowing
InterruptedException. Rethrow it or callThread.currentThread().interrupt(). - Using
Thread.stop(). Useinterrupt()and let the thread stop itself. - Forgetting
join()when you need the work to be finished before moving on. - One new platform thread per task in a server. Platform threads are expensive (about 1 MB of stack each). Use a pool (lesson 3) or virtual threads (lesson 6).
Try it yourself
- In
joinAndSpeedup, delete thejoinAll(baristas)line. What time is printed, and why? - Add a 4th and a 5th drink. Does the parallel time change? Why not?
- In
interruption, delete theThread.currentThread().interrupt()line in thecatch. What happens? (Press Ctrl+C to stop it.)
Next: Synchronization
Threads share the heap, and so far that has been harmless because nobody wrote to the same data at the same time. In the next article, four baristas drop tips into one shared jar using tips++. They should collect 4,000,000 tips. In my run, they collected 2,454,514.
We'll see where the other million and a half went, and three different ways to fix it.
Source code: github.com/baarayy/advanced-java-section · This lesson: Lesson1Threads.java


