What is a thread?
A thread is a path of execution inside a program. Every Java program starts with one thread, main. Multithreading runs several threads at the same time, so a program can download a file while the screen stays responsive, or serve many users at once.
- Process: a running program with its own memory.
- Thread: a lighter unit inside a process; threads of one process share its memory.
Sharing memory makes threads fast to communicate, and also the source of most threading bugs.
Creating a thread
1. Implement Runnable (preferred)
public class Download {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " part " + i);
}
};
Thread t1 = new Thread(task, "File-A");
Thread t2 = new Thread(task, "File-B");
t1.start();
t2.start();
}
}
The output order changes from run to run: the operating system decides when each thread runs.
2. Extend Thread
class Worker extends Thread {
@Override
public void run() {
System.out.println("Working in " + getName());
}
}
new Worker().start();
Implementing Runnable is preferred: your class can still extend another class, and the task is separate from the thread that runs it.
start, not run: t.start() creates a new thread that calls run(). Calling t.run() directly just runs the method in the current thread, with no multithreading.
Thread life cycle
NEW --start()--> RUNNABLE --(waiting for a lock, sleep, join, wait)--> BLOCKED / WAITING / TIMED_WAITING
| |
+<------------------------- back when ready ---------------+
|
run() ends --> TERMINATED
A thread can be started only once; calling start() again throws IllegalThreadStateException.
sleep and join
Thread t = new Thread(() -> {
try {
Thread.sleep(1000); // pause this thread for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Report ready");
});
t.start();
t.join(); // main waits here until t finishes
System.out.println("Printing report");
sleep and join throw the checked InterruptedException, so main needs throws InterruptedException or a try-catch.
Race conditions
When two threads change shared data at the same time, updates can be lost:
public class Race {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable add = () -> { for (int i = 0; i < 100_000; i++) count++; };
Thread a = new Thread(add), b = new Thread(add);
a.start(); b.start();
a.join(); b.join();
System.out.println(count); // often less than 200000!
}
}
count++ is really three steps: read, add 1, write back. If both threads read the same old value, one increment is lost.
synchronized
A synchronized method or block lets only one thread at a time run it for a given object (it holds that object's lock):
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}
A synchronized block locks only the lines that need it:
synchronized (this) {
balance -= amount;
}
Too much locking slows a program down, and two threads each waiting for the other's lock is a deadlock. Keep synchronized sections short and always take locks in the same order.
Atomic variables
For a simple counter, AtomicInteger is safe without locks:
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();
System.out.println(hits.get());
ExecutorService: thread pools
Creating a new thread for every task is costly. An executor keeps a pool of threads and hands them tasks:
import java.util.concurrent.*;
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
int id = i;
pool.submit(() -> System.out.println("Order " + id + " on " + Thread.currentThread().getName()));
}
pool.shutdown(); // no new tasks; finish the queued ones
pool.awaitTermination(5, TimeUnit.SECONDS);
Getting results with Callable and Future
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> f = pool.submit(() -> {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
return sum; // a Callable returns a value
});
System.out.println(f.get()); // waits, then prints 5050
pool.shutdown();
Thread-safe collections
ArrayList and HashMap are not safe to change from several threads. Use ConcurrentHashMap, CopyOnWriteArrayList or a BlockingQueue (for producer-consumer designs).
Virtual threads (Java 21)
Java 21 adds virtual threads: very light threads managed by the JVM, so a server can run thousands of blocking tasks cheaply:
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
exec.submit(() -> System.out.println("Hello from a virtual thread"));
}
Common mistakes
- Calling
run()instead ofstart(). - Changing shared variables from several threads without synchronization or atomics.
- Forgetting
join(), somainprints results before the threads finish. - Forgetting
shutdown()on an executor, so the program never exits. - Swallowing
InterruptedExceptionsilently.
Key points
- A thread is a separate path of execution; threads share their process's memory.
- Create one with a
Runnable(preferred) or by extendingThread; begin it withstart(). sleeppauses;joinwaits for another thread to finish.- Shared mutable data needs
synchronized, locks or atomic classes to avoid race conditions. - Use
ExecutorServicepools,CallableandFutureinstead of creating threads by hand.
Practice questions
1. What is the difference between start() and run()?
start() creates a new thread, which then calls run(). Calling run() directly executes it in the current thread, like any other method.
2. Why can two threads doing count++ 1,000 times each end with less than 2,000?
count++ is read, add, write. If both threads read the same value before either writes, one increment is lost: a race condition.
3. Make this method thread-safe: void deposit(int amt) { balance += amt; }
synchronized void deposit(int amt) {
balance += amt;
}4. Start a thread that prints "Hi" and make main print "Bye" only after it finishes.
Thread t = new Thread(() -> System.out.println("Hi"));
t.start();
t.join();
System.out.println("Bye");5. What does Executors.newFixedThreadPool(4) give you, and why use it?
A pool of 4 reusable threads. Tasks submitted to it share those threads, which is cheaper than creating a thread per task and limits how many run at once.