Thread
A thread is one flow of execution inside your program. Every Java program starts with a single thread, and you create more when you want two pieces of work to make progress at the same time.
Detailed Explanation
Picture a program that downloads a thousand invoices and then totals them. With one thread it does one thing at a time: download, download, download, then add. Almost all of that time is spent waiting on the network while the CPU sits idle. A thread is the unit the scheduler hands CPU time to, so having several of them lets one wait while another works.
Java models a thread as an object of class Thread. You give it a task, call start(), and the runtime creates a new flow of execution that runs that task. The thread that called start() carries on immediately. From that moment the two run independently, and neither one can assume anything about the other's speed.
Before threads were part of mainstream languages, doing two things at once meant running two processes and passing messages between them. Java put threads in the core library from version 1.0 and gave every thread access to the same heap. That shared heap is the source of both the usefulness and every concurrency bug you will ever read about.
A platform thread, the original kind, is backed one-to-one by an operating system thread. It reserves a stack, typically about a megabyte of virtual address space, and swapping between threads goes through the kernel. That is why you cannot have a million of them, and why thread pools exist at all. Java 21 added virtual threads, scheduled by the JVM onto a small pool of carrier threads at a cost of a few hundred bytes each, which changes that arithmetic completely for code that mostly blocks on I/O.
A thread moves through states you can inspect with getState(): NEW before start(), RUNNABLE when it is eligible to run, BLOCKED while waiting to enter a monitor, WAITING or TIMED_WAITING while parked, and TERMINATED once its task returns. A thread runs exactly once. There is no restart.
You cannot safely kill a thread. Thread.stop() was deprecated and then removed because it could abandon shared data halfway through an update. The supported mechanism is interruption: interrupt() sets a flag on the target, and blocking methods such as sleep(), join() and wait() respond by throwing InterruptedException. Cancellation is therefore cooperative. Your task has to check the flag or let the exception propagate, or it will ignore the request entirely.
Two Java Memory Model guarantees are worth memorising. Everything a thread did before calling start() is visible to the new thread. Everything the new thread did is visible to whoever calls join(), once join() returns. Outside those two edges, shared mutable data needs a lock, a volatile field or an atomic class. Without one there is no guarantee about what the other thread sees, and no guarantee about the order it sees things in.
In production code you rarely construct a Thread by hand any more. You hand tasks to an executor, which owns the threads, names them, bounds how many exist and reports failures. Hand-rolled threads cost you all of that, and unbounded thread creation is a dependable way to take a server down.
Code Examples
public class OrderWorkerDemo {
public static void main(String[] args) throws InterruptedException {
// The lambda is the task. Naming the thread makes stack traces readable.
Thread worker = new Thread(() -> {
for (int i = 0; i < 3; i++) {
System.out.println("processing order " + i
+ " on " + Thread.currentThread().getName());
}
}, "order-worker");
worker.start(); // start() runs the task on a NEW thread
worker.join(); // block the main thread until worker finishes
// Safe to read anything the worker wrote: join() creates a happens-before edge.
System.out.println("done on " + Thread.currentThread().getName());
}
}public class CooperativeCancellation {
public static void main(String[] args) throws InterruptedException {
Thread poller = new Thread(() -> {
try {
// Check the flag every loop so cancellation is noticed promptly.
while (!Thread.currentThread().isInterrupted()) {
System.out.println("polling");
Thread.sleep(100); // throws InterruptedException when interrupted
}
} catch (InterruptedException e) {
// sleep() cleared the interrupt flag on the way out.
// Restore it so callers up the stack can still see the cancellation.
Thread.currentThread().interrupt();
}
System.out.println("poller stopped cleanly");
}, "poller");
poller.start();
Thread.sleep(250);
poller.interrupt(); // a polite request, not a kill
poller.join();
}
}public class ThreadBuilders {
public static void main(String[] args) throws InterruptedException {
// Java 21 builder API. A virtual thread is scheduled by the JVM,
// so creating thousands of them is cheap.
Thread virtual = Thread.ofVirtual()
.name("vt-1")
.start(() -> System.out.println(Thread.currentThread()));
// A platform thread is backed 1:1 by an OS thread and is not cheap.
Thread platform = Thread.ofPlatform()
.name("pt-1")
.start(() -> System.out.println(Thread.currentThread()));
virtual.join();
platform.join();
}
}Common Gotchas
Calling `run()` instead of `start()`
`worker.run()` compiles and does the work, but on the calling thread. Nothing runs concurrently and nothing warns you. Only `start()` creates a thread.
Starting the same thread twice
a second `start()` on the same object throws `IllegalThreadStateException`. A `Thread` is single-use; build a new one, or use an executor.
Swallowing `InterruptedException`
catching it and doing nothing destroys the cancellation request, because the blocking method already cleared the flag. Either rethrow it or call `Thread.currentThread().interrupt()` to restore the flag.
An uncaught exception kills only that thread
the rest of the program keeps running. The stack trace goes to the thread's uncaught exception handler, which by default prints to standard error, so a crashed background thread can go unnoticed for hours.