A thread is a line of execution: one path through the code. Every program starts with one, the main thread. Starting more lets a program do several things at once, like serving many web requests or using every core of the processor. It's also where the hardest bugs live, because threads run in an order nobody controls.
Java
Thread worker = new Thread(() -> System.out.println("hello from " + Thread.currentThread().getName()), "worker-1");
worker.start();
worker.join();
System.out.println("main carries on");
Prints
hello from worker-1
main carries on
start() launches the thread, which runs the lambda. join() makes the main thread wait for it to finish. Without the join, the two lines could print in either order.
Race conditions
Trouble starts when threads share data. count++ looks like one step but is three: read count, add one, write it back. Two threads can both read 5, both add one and both write 6, and one increase is lost. This is a race condition:
Java
public class Main {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> { for (int i = 0; i < 100_000; i++) count++; };
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println(count); // should be 200000; often prints less, and differently every run
}
}
Races are nasty because the program usually works: it fails rarely, under load, on someone else's machine. Two fixes. synchronized lets only one thread at a time into a block (others wait their turn). For a simple counter, AtomicInteger does the read-add-write as one indivisible step, without locking:
Java
public class Main {
static int plain = 0;
static final Object lock = new Object();
static final AtomicInteger atomic = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
synchronized (lock) { plain++; }
atomic.incrementAndGet();
}
};
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println(plain + " " + atomic.get());
}
}
Prints
200000 200000
Locks bring their own problem: deadlock, where thread A holds lock 1 and waits for lock 2 while thread B holds lock 2 and waits for lock 1, so both wait forever. Taking locks in the same order everywhere prevents it. The safest shared data is data that never changes: immutable objects like records and strings need no locks at all.
Executors and futures
Making a new thread per task is costly. An executor keeps a pool of threads and hands them tasks. submit returns a Future, a promise of a result you collect later with get(), which waits if it isn't ready. Thread-safe collections like ConcurrentHashMap can be shared between tasks.
Java
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<Integer>> results = new ArrayList<>();
for (int n = 1; n <= 5; n++) {
int x = n;
results.add(pool.submit(() -> x * x));
}
int sum = 0;
for (Future<Integer> f : results) sum += f.get();
pool.shutdown();
System.out.println(sum);
ConcurrentHashMap<String, Integer> hits = new ConcurrentHashMap<>();
try (ExecutorService p2 = Executors.newFixedThreadPool(3)) {
for (int i = 0; i < 300; i++) p2.submit(() -> hits.merge("home", 1, Integer::sum));
}
System.out.println(hits.get("home"));
Prints
55
300
Always shut an executor down, or its threads keep the program alive. Since Java 21 an executor is AutoCloseable: try-with-resources waits for its tasks and shuts it down. merge updates a map entry atomically; doing get then put from several threads would race.
CompletableFuture
A CompletableFuture chains steps that run when the previous one finishes, without blocking a thread to wait, and combines results from several tasks. It's how you'd call two slow services at the same time and use both answers:
Ordinary threads are expensive: each uses an operating-system thread and a big block of memory, so a server can run a few thousand. Java 21 added virtual threads: very cheap threads managed by the JVM, so you can run a million. When one waits for the network or a database, the JVM parks it and uses the real thread for another. They let you write simple one-thread-per-request code that still scales:
Java
AtomicInteger done = new AtomicInteger();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
ex.submit(() -> {
Thread.sleep(10);
return done.incrementAndGet();
});
}
}
System.out.println(done.get() + " tasks finished");
Prints
10000 tasks finished
Ten thousand tasks that each wait 10 ms finish in well under a second, because the waiting doesn't tie up real threads. Virtual threads help work that waits (network, disk, databases); for heavy number-crunching, a fixed pool sized to the number of cores is still right.
Before sharing anything between threads, ask: can it be immutable? If not, use a thread-safe class (AtomicInteger, ConcurrentHashMap) before reaching for your own locks.
Practice
Why can two threads each running count++ 1,000 times end with less than 2,000?
More info
Quick reference
new Thread(r).start() / join()
Run r on a new thread / wait for it.
race condition
Threads interleave on shared data and updates are lost.
synchronized (lock) { }
One thread at a time in the block.
AtomicInteger.incrementAndGet()
A thread-safe counter, no lock.
deadlock
Threads waiting on each other's locks forever.
ExecutorService / submit / Future.get
A thread pool, a task, its result.
ConcurrentHashMap.merge
A thread-safe map and an atomic update.
CompletableFuture
Chain and combine async steps: thenApply, thenCombine, join.