These are the notes for Java episode 39. Ravi runs his chai stall alone: three orders, one pot after another, three minutes. Our program has the same problem: it has one worker that does one thing at a time. We invent threads: a process is the whole stall, the main thread is Ravi, and each extra thread is another cook. We make threads with extends Thread and start(), wait for them with join(), fall into the run() vs start() trap, switch to Runnable and lambdas, and follow a thread through its lifecycle: NEW, RUNNABLE, TIMED_WAITING, TERMINATED. Every example was run with javac 21.
Thread output order can change from run to run. When several threads print, the lines below are one real run; yours may come out in a different order. That's normal, not a bug.
The problem: one chai at a time
To pretend a chai takes time to boil we use Thread.sleep(ms): pause the current thread for that many milliseconds (1000 ms = 1 s).
public class Main {
static void makeChai(String order) {
System.out.println(order + ": boiling...");
Thread.sleep(1000); // boiling takes 1 second
System.out.println(order + ": chai ready");
}
public static void main(String[] args) {
makeChai("masala");
}
}
Output:
Main.java:4: error: unreported exception InterruptedException; must be caught or declared to be thrown
Thread.sleep(1000); // boiling takes 1 second
^
1 error
sleep can be cut short: another thread can interrupt a sleeping thread (shake the cook's shoulder). It warns about that with the checked exception InterruptedException (episode 26), which must be caught or declared.
public class Main {
static void makeChai(String order) {
System.out.println(order + ": boiling...");
try {
Thread.sleep(1000); // boiling takes 1 second
} catch (InterruptedException e) {
System.out.println(order + ": interrupted!");
}
System.out.println(order + ": chai ready");
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
makeChai("masala");
makeChai("ginger");
makeChai("lemon");
long ms = System.currentTimeMillis() - start;
System.out.println("All served in " + Math.round(ms / 1000.0) + " s");
}
}
Output:
masala: boiling...
masala: chai ready
ginger: boiling...
ginger: chai ready
lemon: boiling...
lemon: chai ready
All served in 3 s
Three orders, three seconds. The program has exactly one worker running its code, and while a pot boils it just waits. That single path of execution is a thread.
Process and threads
Real-life example: a stall with more cooks.
| At the chai stall | In Java | Meaning |
|---|---|---|
| The whole stall: stoves, milk, cash box | Process | a running program, with its own memory given by the operating system |
| Ravi, who opens the stall | main thread | the thread the JVM creates to run main() |
| Extra cooks sharing the stall | Threads | separate paths of execution inside one process, sharing its memory (the heap) |
Every program already has at least one thread:
public class Main {
public static void main(String[] args) {
Thread me = Thread.currentThread();
System.out.println("name: " + me.getName());
System.out.println("state: " + me.getState());
System.out.println("cores: " + Runtime.getRuntime().availableProcessors());
}
}
Output:
name: main
state: RUNNABLE
cores: 2
Each thread has its own call stack (its own local variables), but all threads of a process share the heap (the objects). That sharing is what makes threads powerful, and what episode 40 is about.
extends Thread, run() and start()
java.lang.Thread is Java's worker. Extend it, override run() (the job), and call start():
class Cook extends Thread {
private final String order;
Cook(String order) { this.order = order; }
@Override public void run() {
System.out.println(order + ": boiling on " + getName());
try { Thread.sleep(1000); } catch (InterruptedException e) { }
System.out.println(order + ": chai ready");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Cook a = new Cook("masala"), b = new Cook("ginger"), c = new Cook("lemon");
a.start(); b.start(); c.start();
long ms = System.currentTimeMillis() - start;
System.out.println("All served in " + Math.round(ms / 1000.0) + " s");
}
}
Output:
lemon: boiling on Thread-2
masala: boiling on Thread-0
All served in 0 s
ginger: boiling on Thread-1
lemon: chai ready
masala: chai ready
ginger: chai ready
start()asks the JVM to create a new thread, which then callsrun().start()returns immediately. That's whymainprinted "All served in 0 s" before any chai was ready.- Threads get default names
Thread-0,Thread-1, ... andgetName()returns them.
join(): wait for a thread to finish
t.join() makes the calling thread wait until t has finished. join can also be interrupted, so main declares throws InterruptedException.
class Cook extends Thread {
private final String order;
Cook(String order) { this.order = order; }
@Override public void run() {
System.out.println(order + ": boiling on " + getName());
try { Thread.sleep(1000); } catch (InterruptedException e) { }
System.out.println(order + ": chai ready");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Cook a = new Cook("masala"), b = new Cook("ginger"), c = new Cook("lemon");
a.start(); b.start(); c.start();
a.join(); b.join(); c.join(); // wait for all three
long ms = System.currentTimeMillis() - start;
System.out.println("All served in " + Math.round(ms / 1000.0) + " s");
}
}
Output:
masala: boiling on Thread-0
ginger: boiling on Thread-1
lemon: boiling on Thread-2
ginger: chai ready
masala: chai ready
lemon: chai ready
All served in 1 s
The three one-second waits now overlap: 1 second instead of 3. join(ms) waits at most that long.
run() is not start()
class Cook extends Thread {
private final String order;
Cook(String order) { this.order = order; }
@Override public void run() {
String who = Thread.currentThread().getName();
System.out.println(order + ": boiling on " + who);
try { Thread.sleep(1000); } catch (InterruptedException e) { }
System.out.println(order + ": chai ready");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Cook a = new Cook("masala"), b = new Cook("ginger"), c = new Cook("lemon");
a.run(); b.run(); c.run(); // run(), not start()
long ms = System.currentTimeMillis() - start;
System.out.println("All served in " + Math.round(ms / 1000.0) + " s");
}
}
Output:
masala: boiling on main
masala: chai ready
ginger: boiling on main
ginger: chai ready
lemon: boiling on main
lemon: chai ready
All served in 3 s
Calling run() is just an ordinary method call: no new thread is created, and main does all the work itself, one after another. Thread.currentThread() returns the thread executing the current line, which proves it: main.
Note: inside a Thread subclass, getName() is the name of that Thread object, even if main is the one running the code. Thread.currentThread().getName() tells you who is really running.
Rule: write run(), call start().
Runnable and lambdas
A Java class can extend only one class (episode 18). If Cook already extends Staff, it can't extend Thread too:
class Staff {
String name = "Ravi";
}
class Cook extends Staff, Thread {
public void run() {
System.out.println(name + " is cooking");
}
}
public class Main {
public static void main(String[] args) {
new Cook().start();
}
}
Output:
Main.java:5: error: '{' expected
class Cook extends Staff, Thread {
^
1 error
Real-life example: the recipe card and the cook.
| At the stall | In Java | Meaning |
|---|---|---|
| A recipe card: what to do, not who | Runnable |
an interface with one method, void run() |
| A cook who follows any card | Thread |
new Thread(runnable) runs that job |
| A sticky note for a quick job | a lambda | () -> ... is a Runnable (episode 36) |
class Staff { String name; Staff(String name) { this.name = name; } }
class Cook extends Staff implements Runnable {
Cook(String name) { super(name); }
public void run() {
String t = Thread.currentThread().getName();
System.out.println(name + " cooks on " + t);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Cook("Ravi"), "stove-1");
Thread t2 = new Thread(() -> System.out.println("Asha serves on "
+ Thread.currentThread().getName()), "counter");
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("main runs on " + Thread.currentThread().getName());
}
}
Output:
Asha serves on counter
Ravi cooks on stove-1
main runs on main
new Thread(job, "name") sets the thread's name. Prefer Runnable (or a lambda): your class stays free to extend another class, one job can be given to many threads, and the job is separate from the worker. (Episode 41 hands jobs to a pool of threads instead of creating them by hand.)
extends Thread |
implements Runnable |
|---|---|
uses up the one extends |
class can still extend another class |
| job and worker glued together | job separate from worker |
new Cook().start() |
new Thread(job).start() |
The life of a thread
| State | When |
|---|---|
NEW |
created with new Thread(...), start() not called yet |
RUNNABLE |
after start(): running, or ready to run when a CPU core is free |
BLOCKED |
waiting to take a lock held by another thread (episode 40) |
WAITING |
waiting with no time limit: join(), wait() |
TIMED_WAITING |
waiting for a fixed time: sleep(ms), join(ms) |
TERMINATED |
run() has ended |
The states are the enum Thread.State, and getState() returns the current one.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread cook = new Thread(() -> {
long until = System.currentTimeMillis() + 300;
while (System.currentTimeMillis() < until) { } // chopping: busy
try { Thread.sleep(800); } catch (InterruptedException e) { }
});
System.out.println("1. " + cook.getState()); // created, not started
cook.start();
System.out.println("2. " + cook.getState()); // chopping
Thread.sleep(600);
System.out.println("3. " + cook.getState()); // boiling: sleeping
cook.join();
System.out.println("4. " + cook.getState()); // finished
}
}
Output:
1. NEW
2. RUNNABLE
3. TIMED_WAITING
4. TERMINATED
WAITING and BLOCKED in a real run (the lock part is explained fully in episode 40):
public class Main {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
Thread waiter = new Thread(() -> {
synchronized (lock) {
try { lock.wait(); } catch (InterruptedException e) { }
}
});
Thread blocked = new Thread(() -> { synchronized (lock) { } });
waiter.start();
Thread.sleep(200);
synchronized (lock) {
blocked.start();
Thread.sleep(200);
System.out.println("waiter: " + waiter.getState());
System.out.println("blocked: " + blocked.getState());
lock.notifyAll();
}
waiter.join(); blocked.join();
System.out.println("both: " + waiter.getState() + ", " + blocked.getState());
}
}
Output:
waiter: WAITING
blocked: BLOCKED
both: TERMINATED, TERMINATED
A thread starts only once
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread cook = new Thread(() -> System.out.println("one chai made"));
cook.start();
cook.join();
System.out.println("state: " + cook.getState());
cook.start(); // start the same thread again?
}
}
Output:
one chai made
state: TERMINATED
Exception in thread "main" java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.start(Thread.java:1525)
at Main.main(Main.java:7)
A thread's life only goes forward. For more work, create a new Thread with the same Runnable.
Extra: interrupting, and daemon threads
interrupt() wakes a thread that is sleeping or waiting: its sleep throws InterruptedException.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread cook = new Thread(() -> {
try {
System.out.println("cook: napping for 5 s");
Thread.sleep(5000);
System.out.println("cook: woke up on time");
} catch (InterruptedException e) {
System.out.println("cook: woken early!");
}
});
cook.start();
Thread.sleep(300);
cook.interrupt(); // shake his shoulder
cook.join();
}
}
Output:
cook: napping for 5 s
cook: woken early!
A daemon thread is a background helper: the JVM exits when only daemon threads are left. Normal threads (the default) keep the program alive until they finish.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread radio = new Thread(() -> {
while (true) {
System.out.println("radio playing...");
try { Thread.sleep(300); } catch (InterruptedException e) { }
}
});
radio.setDaemon(true); // background helper: doesn't keep the program alive
radio.start();
Thread.sleep(700);
System.out.println("main ends, so the program ends");
}
}
Output:
radio playing...
radio playing...
radio playing...
main ends, so the program ends
How much faster?
| Version | Time for three 1-second chais |
|---|---|
| one thread | 3 s: the waits add up |
three threads + join |
1 s: the waits overlap |
Threads help most when work spends its time waiting (files, the network, a timer). For heavy calculation, a computer can truly run only as many threads at once as it has CPU cores; more threads than that take turns.
Common mistakes (and the real error messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
Thread.sleep(1000); with no try/catch |
error: unreported exception InterruptedException; must be caught or declared to be thrown |
sleep can be interrupted |
try { ... } catch (InterruptedException e) or throws InterruptedException |
cook.run(); |
no error: runs on main, one after another |
run() is a plain method call |
cook.start() |
class Cook extends Staff, Thread |
error: '{' expected |
a class extends only one class | extends Staff implements Runnable |
cook.start(); ... cook.start(); |
java.lang.IllegalThreadStateException |
a thread starts only once | new Thread(job).start() |
forgetting join() |
no error: main goes on without waiting |
start() returns immediately |
t.join() before using the results |
Mini project: the morning rush
Four kitchen jobs of different lengths, first done by main alone, then by a team of named threads. The total time drops from the sum of the jobs to the longest job.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void work(String what, int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { }
System.out.println("done: " + what + " (" + ms + " ms) on " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
String[] jobs = {"boil milk", "fry samosas", "toast bread", "wash cups"};
int[] times = {800, 600, 400, 300};
long t0 = System.currentTimeMillis();
for (int i = 0; i < jobs.length; i++) work(jobs[i], times[i]);
long alone = System.currentTimeMillis() - t0;
t0 = System.currentTimeMillis();
List<Thread> team = new ArrayList<>();
for (int i = 0; i < jobs.length; i++) {
String job = jobs[i]; int ms = times[i];
Thread t = new Thread(() -> work(job, ms), "cook-" + (i + 1));
team.add(t);
t.start();
}
for (Thread t : team) t.join();
long together = System.currentTimeMillis() - t0;
System.out.println("Alone: about " + Math.round(alone / 100.0) * 100 + " ms");
System.out.println("Together: about " + Math.round(together / 100.0) * 100 + " ms");
}
}
Output:
done: boil milk (800 ms) on main
done: fry samosas (600 ms) on main
done: toast bread (400 ms) on main
done: wash cups (300 ms) on main
done: wash cups (300 ms) on cook-4
done: toast bread (400 ms) on cook-3
done: fry samosas (600 ms) on cook-2
done: boil milk (800 ms) on cook-1
Alone: about 2100 ms
Together: about 800 ms
Practice
- Two threads: one prints 1 to 5, the other A to E.
- Time four fake 1-second downloads, with one thread and with four threads.
- Give your threads names and print them from inside the job.
- Print a thread's state before
start()and afterjoin().
Solution 1
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread numbers = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try { Thread.sleep(100); } catch (InterruptedException e) { }
}
});
Thread letters = new Thread(() -> {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println(c);
try { Thread.sleep(100); } catch (InterruptedException e) { }
}
});
numbers.start(); letters.start();
numbers.join(); letters.join();
System.out.println("both finished");
}
}
Output:
1
A
B
2
C
3
4
D
5
E
both finished
Solution 2
public class Main {
static void download(String file) {
try { Thread.sleep(1000); } catch (InterruptedException e) { }
}
public static void main(String[] args) throws InterruptedException {
String[] files = {"a.pdf", "b.pdf", "c.pdf", "d.pdf"};
long t0 = System.currentTimeMillis();
for (String f : files) download(f);
System.out.println("one thread: " + Math.round((System.currentTimeMillis() - t0) / 1000.0) + " s");
t0 = System.currentTimeMillis();
Thread[] ts = new Thread[files.length];
for (int i = 0; i < files.length; i++) {
String f = files[i];
ts[i] = new Thread(() -> download(f));
ts[i].start();
}
for (Thread t : ts) t.join();
System.out.println("four threads: " + Math.round((System.currentTimeMillis() - t0) / 1000.0) + " s");
}
}
Output:
one thread: 4 s
four threads: 1 s
Solution 3
public class Main {
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> System.out.println("hello from " + Thread.currentThread().getName());
Thread a = new Thread(job, "billing");
Thread b = new Thread(job);
b.setName("kitchen");
a.start(); b.start();
a.join(); b.join();
}
}
Output:
hello from billing
hello from kitchen
Solution 4
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> System.out.println("working"));
System.out.println("before start: " + t.getState());
t.start();
t.join();
System.out.println("after join: " + t.getState());
}
}
Output:
before start: NEW
working
after join: TERMINATED
Quick quiz
What does this print?
Thread t = new Thread(() ->
System.out.print("A"));
t.run();
t.run();
System.out.print(t.getState());
A. AANEW B. AATERMINATED C. A, then IllegalThreadStateException D. AARUNNABLE
Answer
A. run() is a plain method call on main, so it can be called twice and prints AA. start() was never called, so the thread is still NEW.
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.print("A"));
t.run();
t.run();
System.out.print(t.getState());
System.out.println();
}
}
Output:
AANEW
Interview questions
- Process vs thread? A process is a running program with its own memory; threads are paths of execution inside a process that share its heap but each have their own stack.
- Two ways to create a thread? Extend
Threadand overriderun(), or implementRunnable(often a lambda) and pass it tonew Thread(...). PreferRunnable. (AlsoCallablewith executors, episode 41.) start()vsrun()?start()creates a new thread that then callsrun(); callingrun()directly runs the code on the current thread.- What does
join()do? The calling thread waits until the other thread finishes. - Can a thread be started twice? No:
IllegalThreadStateException. - What are the thread states?
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED. - Why does
sleepthrowInterruptedException? Another thread may interrupt it withinterrupt(); the checked exception forces you to decide what to do then. - What is a daemon thread? A background thread that doesn't keep the JVM alive; set with
setDaemon(true)beforestart(). - Does
Thread.sleeprelease locks? No. (Episode 40.)
Glossary
| Term | Meaning |
|---|---|
| Process | a running program with its own memory and resources |
| Thread | one path of execution inside a process; threads share the process's heap |
| Main thread | the thread the JVM creates to run main() |
| Multithreading | a program running several threads at the same time |
| Concurrency | several tasks in progress at once, possibly taking turns |
Thread |
the Java class representing a thread |
run() |
the method holding a thread's job |
start() |
creates the new thread, which then calls run(); returns immediately |
join() |
waits until a thread finishes |
Thread.sleep(ms) |
pauses the current thread for that many milliseconds |
InterruptedException |
checked exception thrown when a sleeping/waiting thread is interrupted |
interrupt() |
asks a thread to stop waiting/sleeping |
Runnable |
an interface with one method run(): a job a thread can run |
| Lambda | a short way to write a one-method interface such as Runnable |
Thread.currentThread() |
the thread executing the current line |
getName() / setName() |
a thread's name (default Thread-0, Thread-1, ...) |
getState() |
the thread's current state (Thread.State) |
NEW |
created, not started |
RUNNABLE |
running or ready to run |
BLOCKED |
waiting for a lock |
WAITING |
waiting with no time limit (join, wait) |
TIMED_WAITING |
waiting for a fixed time (sleep, join(ms)) |
TERMINATED |
finished |
IllegalThreadStateException |
thrown when start() is called on a thread that was already started |
| Daemon thread | a background thread that doesn't keep the program alive |
| CPU core | one processing unit; it runs one thread at a time |
Summary
- A process is a running program; threads are workers inside it that share its memory.
mainruns on the main thread. - Make a thread with
extends Thread+run(), or better, aRunnable/lambda passed tonew Thread(...). - Write
run(), callstart(). Callingrun()directly runs on the current thread. start()doesn't wait: usejoin()to wait for a thread to finish.Thread.sleepthrows the checkedInterruptedException.- A thread goes
NEW→RUNNABLE→ (BLOCKED/WAITING/TIMED_WAITING) →TERMINATED, and can be started only once. - Threads speed up work that waits; for pure calculation the limit is the number of CPU cores.
- Next episode: synchronization, deadlock and
volatile: what goes wrong when threads share data.