Java Threads
A thread is an independent path of execution inside a program. Every Java program starts with one thread — the main thread — but you can start more so that several tasks run at the same time: downloading files while the user interface stays responsive, or splitting a big calculation across all CPU cores.
Note: The online sandbox that runs ExcelTAD playgrounds does not allow programs to create extra operating-system threads, so most examples in this chapter are shown with their expected output instead of a Run button. Copy them into a local project to try them. They are written to be deterministic: threads do their work, the main thread waits for them with
join(), and results are printed in a fixed order.
The current thread
Even a program that never creates a thread runs inside one. Thread.currentThread() returns the thread executing the current code:
class Main {
public static void main(String[] args) {
Thread current = Thread.currentThread();
System.out.println("Running in: " + current.getName());
System.out.println("Is daemon: " + current.isDaemon());
Thread worker = new Thread(() ->
System.out.println("Task runs in: " + Thread.currentThread().getName()), "worker-1");
System.out.println(worker.getName() + " state: " + worker.getState());
worker.run(); // NOT start(): the task simply runs in the main thread
System.out.println(worker.getName() + " state: " + worker.getState());
}
}Running in: main
Is daemon: false
worker-1 state: NEW
Task runs in: main
worker-1 state: NEW
Calling run() directly executed the task in main, and the thread object never left the NEW state. Only start() creates a real new thread.
Creating and starting a thread
Give a Thread a Runnable — usually a lambda — describing the work, then call start(). join() makes the current thread wait until the other thread has finished:
class Main {
public static void main(String[] args) throws InterruptedException {
long[] result = new long[1];
Thread worker = new Thread(() -> {
long sum = 0;
for (int i = 1; i <= 1_000_000; i++) sum += i;
result[0] = sum;
});
System.out.println("State before start: " + worker.getState());
worker.start(); // runs the lambda in a new thread
worker.join(); // wait for it to finish
System.out.println("State after join: " + worker.getState());
System.out.println("Sum: " + result[0]);
}
}State before start: NEW
State after join: TERMINATED
Sum: 500000500000
Note: Call
start(), notrun(). Callingrun()directly just executes the code in the current thread — no new thread is created.
You can also extend Thread and override run(), but passing a Runnable is more flexible because your class remains free to extend something else.
Splitting work across threads
Each thread below sums one part of an array and stores its result in its own slot. After joining all threads, the main thread combines the partial results:
class Main {
public static void main(String[] args) throws InterruptedException {
int[] data = new int[1000];
for (int i = 0; i < data.length; i++) data[i] = i + 1;
int parts = 4;
long[] partial = new long[parts];
Thread[] threads = new Thread[parts];
int chunk = data.length / parts;
for (int t = 0; t < parts; t++) {
final int id = t;
threads[t] = new Thread(() -> {
long s = 0;
for (int i = id * chunk; i < (id + 1) * chunk; i++) s += data[i];
partial[id] = s;
});
threads[t].start();
}
for (Thread th : threads) th.join();
long total = 0;
for (int t = 0; t < parts; t++) {
System.out.println("Part " + t + ": " + partial[t]);
total += partial[t];
}
System.out.println("Total: " + total);
}
}Part 0: 31375
Part 1: 93875
Part 2: 156375
Part 3: 218875
Total: 500500
A lambda can only use local variables that are effectively final, which is why the loop variable is copied into id.
Race conditions
When several threads modify the same variable, their steps can interleave and updates get lost. count++ looks like one step but is really three: read, add, write. Here's how to make it safe:
import java.util.concurrent.atomic.AtomicInteger;
class Counter {
private int value = 0;
synchronized void increment() { // only one thread at a time
value++;
}
int get() { return value; }
}
class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
AtomicInteger atomic = new AtomicInteger();
Runnable task = () -> {
for (int i = 0; i < 10_000; i++) {
counter.increment();
atomic.incrementAndGet();
}
};
Thread a = new Thread(task);
Thread b = new Thread(task);
a.start();
b.start();
a.join();
b.join();
System.out.println("synchronized: " + counter.get());
System.out.println("atomic: " + atomic.get());
}
}synchronized: 20000
atomic: 20000
Without synchronized (or an atomic class), the final count would often be less than 20000 — and different on every run.
| Tool | Use it for |
|---|---|
synchronized method/block |
protect a section of code with a lock |
AtomicInteger, AtomicLong |
lock-free counters and flags |
ConcurrentHashMap |
a map shared between threads |
volatile |
a flag that one thread writes and others read |
Executors and futures
Creating threads by hand is fine for learning, but real code uses an ExecutorService — a pool of threads that runs tasks you submit. A Callable task returns a value, delivered through a Future:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class Main {
static long countPrimes(int from, int to) {
long count = 0;
for (int n = Math.max(2, from); n < to; n++) {
boolean prime = true;
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) { prime = false; break; }
}
if (prime) count++;
}
return count;
}
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
List<Future<Long>> futures = new ArrayList<>();
for (int start = 0; start < 30_000; start += 10_000) {
final int s = start;
futures.add(pool.submit(() -> countPrimes(s, s + 10_000)));
}
long total = 0;
for (int i = 0; i < futures.size(); i++) {
long c = futures.get(i).get(); // waits for that task
System.out.println("Range " + i + ": " + c + " primes");
total += c;
}
System.out.println("Primes below 30000: " + total);
}
}
}Range 0: 1229 primes
Range 1: 1033 primes
Range 2: 983 primes
Primes below 30000: 3245
Since Java 19 an ExecutorService can be used in try-with-resources: closing it waits for submitted tasks to finish.
Virtual threads
Java 21 introduced virtual threads — extremely lightweight threads managed by the JVM. You can start hundreds of thousands of them, which is ideal for servers that spend most of their time waiting on I/O:
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
class Main {
public static void main(String[] args) {
AtomicLong done = new AtomicLong();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> done.incrementAndGet());
}
} // waits for all 10,000 tasks
System.out.println("Tasks completed: " + done.get());
Thread vt = Thread.ofVirtual().unstarted(() -> {});
System.out.println("Is virtual: " + vt.isVirtual());
}
}Tasks completed: 10000
Is virtual: true
Tip: Prefer high-level tools — executors, futures, concurrent collections and parallel streams — over raw threads and locks. They're easier to get right.
Test yourself
Which method begins executing a thread's task in a new thread?
- run()
- start()
- execute()
- join()
What does t.join() do?
- Merges two threads
- Starts t
- Waits until thread t has finished
- Stops thread t
Two threads each run count++ 1000 times on a shared int without synchronization. What is the result?
- Always 2000
- Always 1000
- Possibly less than 2000, varying between runs
- A compile error