Essay
Learning Java, Part 11: Multithreaded Programming
Study notes on threads and the Runnable interface, creating and joining threads, priorities, race conditions, synchronized methods and blocks, wait and notify, why suspend and stop were removed, the main thread, and the modern java.util.concurrent tools. Written entirely by an AI model.
A thread is a separate path of execution inside one program. All threads share the program’s memory, which makes them powerful and dangerous at once. Concurrency is one of the four CITS2005 learning outcomes, and it is the topic Python programmers have usually met least.
Why threads
- To do slow things (downloads, file reads) without freezing the rest of the program.
- To use several CPU cores for one job.
On a single core, threads take turns, switched by the operating system’s scheduler. You cannot predict the order in which they run. Every bug in this part comes from that fact.
Creating a thread
There are two ways:
- Implement
Runnable(one method,run()) and pass it to aThread. This is the preferred way, because your class stays free to extend something else. - Extend
Threadand overriderun().
Either way, you call start(), which creates the new thread and calls run() on it. Calling run() directly just runs the code on the current thread, with no concurrency. That is a classic mistake.
public class TwoWorkers {
static class Counter implements Runnable {
private final String name;
private int total;
Counter(String name) { this.name = name; }
public void run() {
for (int i = 1; i <= 1000; i++) total += i;
}
int total() { return total; }
}
public static void main(String[] args) throws InterruptedException {
Counter a = new Counter("A");
Counter b = new Counter("B");
Thread ta = new Thread(a);
Thread tb = new Thread(b, "worker-B"); // optional name
ta.start();
tb.start();
ta.join(); // wait until ta finishes
tb.join();
System.out.println(a.total() + b.total());
System.out.println(ta.isAlive());
}
}
1001000
false
join()waits for a thread to end. Without it,mainmight print before the workers finish.isAlive()tells you whether a thread is still running.Thread.sleep(ms)pauses the current thread. Bothsleepandjointhrow the checkedInterruptedException, which is whymaindeclares it.- Since
Runnablehas one method, you can also writenew Thread(() -> { ... })with a lambda (Part 14).
Priorities
setPriority(n) takes a value from Thread.MIN_PRIORITY (1) to MAX_PRIORITY (10), with NORM_PRIORITY (5) as the default. It is only a hint to the scheduler, and its effect varies by operating system. Never rely on priorities for correctness.
The race condition
When two threads read and write the same variable, their steps can interleave. count++ looks like one step, but it is three: read count, add one, write it back. If both threads read the same old value, one increment is lost.
public class Race {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) count++;
};
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(count); // expected 200000; usually prints less
}
}
Run it a few times. The answer changes from run to run and is usually below 200,000. A program whose result depends on timing like this has a race condition. These bugs are hard to find because they may not appear in testing.
synchronized
Every object has a built-in lock (also called a monitor). A synchronized method acquires the lock of its object before running and releases it afterwards, so only one thread at a time can be inside any synchronized method of that object.
public class SafeCount {
private int count = 0;
synchronized void increment() { count++; }
synchronized int get() { return count; }
public static void main(String[] args) throws InterruptedException {
SafeCount c = new SafeCount();
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) c.increment();
};
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get());
}
}
200000
- A
synchronizedblock,synchronized (someObject) { ... }, locks a chosen object for just part of a method. Use it to keep the locked section short, or to synchronise access to an object whose class you cannot change. - A
static synchronizedmethod locks theClassobject, which is shared by all instances. - Reads need synchronising too. Without it, one thread may not see another thread’s write at all (a visibility problem). That is why
get()is synchronized as well.
Deadlock
If thread 1 holds lock A and waits for lock B, while thread 2 holds B and waits for A, both wait forever. That is a deadlock. The standard defence is to make every thread acquire locks in the same order.
wait, notify and notifyAll
Sometimes a thread must wait until another thread changes something, such as a queue becoming non-empty. Checking in a loop wastes CPU. Instead:
wait()releases the lock and sleeps until another thread callsnotifyon the same object.notify()wakes one waiting thread;notifyAll()wakes all of them.- All three must be called while holding the object’s lock, inside synchronized code. Otherwise they throw
IllegalMonitorStateException. - Always call
wait()inside awhileloop that rechecks the condition. A thread can wake without being notified (a “spurious wakeup”), or find that another thread got there first.
public class Handoff {
private String item; // a one-slot buffer
synchronized void put(String s) throws InterruptedException {
while (item != null) wait();
item = s;
notifyAll();
}
synchronized String take() throws InterruptedException {
while (item == null) wait();
String s = item;
item = null;
notifyAll();
return s;
}
public static void main(String[] args) throws InterruptedException {
Handoff h = new Handoff();
Thread producer = new Thread(() -> {
try {
for (String s : new String[] {"tick", "tock", "tick"}) h.put(s);
h.put("done");
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start();
String s;
while (!(s = h.take()).equals("done")) System.out.println(s);
producer.join();
}
}
tick
tock
tick
This is the producer-consumer pattern, and the book’s tick-tock example works the same way.
Suspending and stopping threads
Early Java had suspend(), resume() and stop(). They were deprecated because stopping a thread mid-step could leave shared objects half-updated, and a thread suspended while holding a lock froze everyone waiting for it. Current JDKs have removed them entirely, so the book’s examples that call them do not compile. The safe pattern, which the book also shows, is a flag the thread checks itself, or interruption: another thread calls t.interrupt(), and the target notices through Thread.interrupted() or an InterruptedException from sleep or wait, then finishes cleanly.
The main thread
main runs on a thread called main. Thread.currentThread() returns the thread you are on, so you can get its name or priority.
The modern toolkit
Java 5 added java.util.concurrent, which you should prefer to raw threads in real code:
- Executors run tasks on a pool of reusable threads and return
Futureresults. - Atomic classes such as
AtomicIntegergive lock-freeincrementAndGet(). - Concurrent collections such as
ConcurrentHashMapandBlockingQueue(a ready-made producer-consumer buffer). ReentrantLockoffers whatsynchronizeddoes, plus timeouts.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Pool {
public static void main(String[] args) throws Exception {
AtomicInteger hits = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
Future<Integer> sum = pool.submit(() -> {
int s = 0;
for (int i = 1; i <= 100; i++) s += i;
return s;
});
for (int i = 0; i < 1000; i++) pool.submit(() -> hits.incrementAndGet());
System.out.println(sum.get()); // waits for the result
} // close() waits for all tasks
System.out.println(hits.get());
}
}
5050
1000
Modern Java. Java 21 added virtual threads, which are cheap enough to create one per task in the millions: Executors.newVirtualThreadPerTaskExecutor(). ExecutorService became AutoCloseable in Java 19, which is why the try-with-resources above works.
Exam-style checks
- Give the two ways of creating a thread, and explain why implementing
Runnableis usually preferred. - What is the difference between calling
start()and callingrun()? - Explain why
count++is not safe across threads, and fix it in two different ways. - Why must
wait()be called inside a loop, and inside synchronized code? - What is a deadlock, and how can lock ordering prevent it?
Where to practise
Run the race example ten times and record the results, then fix it with synchronized and again with AtomicInteger. Rewrite the handoff example using ArrayBlockingQueue and compare the length. Schildt’s Chapter 11 also has a short exercise on the main thread’s name and priority.