Introduction & Syntax
Multithreading · Study material
A thread is an independent path of execution inside a program. Every Java program starts with one – the main thread – and can create more so that several tasks run at the same time: a server handling many users, an app downloading files while the UI stays responsive, or a calculation split across all CPU cores. Multithreading makes programs faster and more responsive, but threads share the same memory, which brings new kinds of bugs: race conditions (updates lost when two threads change the same data), visibility problems (one thread not seeing another's write), and deadlocks (threads waiting for each other forever). This page covers creating and controlling threads, the thread lifecycle, sleep, join and interrupt, synchronized and volatile, wait/notify, deadlock avoidance and ThreadLocal – with programs written so that their output is the same on every run. The high-level tools (executors, futures, locks, atomics, concurrent collections) come in the next topic. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- Creating threads: Thread, Runnable, lambdas; start vs run
- The thread lifecycle and states
- sleep, join, interrupt, daemon threads and priorities
- Race conditions and synchronized
- volatile and visibility; wait, notify and producer–consumer
- Deadlock, ThreadLocal and thread-safety strategies
Creating threads
Put the work in a run() method – by extending Thread, by implementing Runnable (preferred, since the class stays free to extend another class), or with a lambda. Then call start(). The order in which threads run and finish is decided by the scheduler, so never assume it.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static final List<String> LOG = Collections.synchronizedList(new ArrayList<>());
// 1. Extend Thread and override run()
static class Downloader extends Thread {
Downloader(String name) { super(name); }
@Override public void run() { LOG.add(getName() + " downloaded"); }
}
// 2. Implement Runnable (preferred: the class can still extend something else)
static class Uploader implements Runnable {
@Override public void run() { LOG.add(Thread.currentThread().getName() + " uploaded"); }
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Downloader("worker-1");
Thread t2 = new Thread(new Uploader(), "worker-2");
Thread t3 = new Thread(() -> LOG.add(Thread.currentThread().getName() + " resized"), "worker-3"); // 3. a lambda
t1.start(); t2.start(); t3.start(); // start() creates a new thread that calls run()
t1.join(); t2.join(); t3.join(); // wait for all three to finish
Collections.sort(LOG); // the threads may finish in ANY order – sort before printing
LOG.forEach(System.out::println);
System.out.println("main thread: " + Thread.currentThread().getName());
}
}
worker-1 downloaded worker-2 uploaded worker-3 resized main thread: main
start() vs run()
start() asks the JVM to create a new thread that will call run(). Calling run() yourself just executes it in the current thread – no concurrency at all. A thread object can be started only once.
public class Main {
public static void main(String[] args) throws InterruptedException {
String[] seen = new String[2];
Thread t = new Thread(() -> {
String name = Thread.currentThread().getName();
if (seen[0] == null) seen[0] = name; else seen[1] = name;
}, "worker");
t.run(); // ✘ just a normal method call – runs in the CURRENT thread (main)
t.start(); // ✔ starts a new thread named "worker"
t.join();
System.out.println("run() executed in: " + seen[0]);
System.out.println("start() executed in: " + seen[1]);
try {
t.start(); // a thread can be started only once
} catch (IllegalThreadStateException e) {
System.out.println("cannot start a thread twice");
}
}
}
run() executed in: main start() executed in: worker cannot start a thread twice
The thread lifecycle
| State | Meaning |
|---|---|
| NEW | created, start() not called yet |
| RUNNABLE | running or ready to run |
| BLOCKED | waiting to enter a synchronized block held by another thread |
| WAITING | waiting indefinitely – wait(), join() with no timeout |
| TIMED_WAITING | sleep(ms), wait(ms), join(ms) |
| TERMINATED | run() has finished |
public class Main {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
Thread sleeper = new Thread(() -> {
try { Thread.sleep(300); } catch (InterruptedException e) { }
});
Thread waiter = new Thread(() -> {
synchronized (lock) {
try { lock.wait(); } catch (InterruptedException e) { }
}
});
System.out.println("before start: " + sleeper.getState()); // NEW
sleeper.start();
waiter.start();
while (sleeper.getState() != Thread.State.TIMED_WAITING) Thread.onSpinWait();
while (waiter.getState() != Thread.State.WAITING) Thread.onSpinWait();
System.out.println("sleeping: " + sleeper.getState()); // TIMED_WAITING
System.out.println("waiting: " + waiter.getState()); // WAITING
synchronized (lock) { lock.notify(); } // wake the waiter
sleeper.join();
waiter.join();
System.out.println("finished: " + sleeper.getState() + " " + waiter.getState() + " " + sleeper.isAlive());
}
}
before start: NEW sleeping: TIMED_WAITING waiting: WAITING finished: TERMINATED TERMINATED false
Race conditions and synchronized
count++ is three steps – read, add, write – so two threads can read the same old value and one update is lost. synchronized makes a method or block a critical section: a thread must hold the object's lock (its monitor) to enter, so only one thread runs it at a time. A synchronized instance method locks this; a static one locks the class object. Locks are re-entrant: a thread that holds a lock can enter other code guarded by the same lock.
public class Main {
static int unsafeCount = 0;
static int safeCount = 0;
static synchronized void safeIncrement() { safeCount++; } // one thread at a time (lock on Main.class)
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
unsafeCount++; // read – add – write: NOT atomic, updates can be lost
safeIncrement();
}
};
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(work); threads[i].start(); }
for (Thread t : threads) t.join();
int expected = 4 * 100_000;
System.out.println("expected " + expected);
System.out.println("synchronized count correct: " + (safeCount == expected));
System.out.println("unsafe count never exceeds it: " + (unsafeCount <= expected));
// On most runs unsafeCount is LESS than 400000 – the exact value changes every time.
}
}
expected 400000 synchronized count correct: true unsafe count never exceeds it: true
Synchronized blocks
Lock only the part that needs it, preferably on a private lock object. Compound actions such as check-then-act ("if balance ≥ amount, withdraw") must happen inside one synchronized block, or two threads can both pass the check.
public class Main {
static class Account {
private final String id;
private long balance;
private final Object lock = new Object(); // a private lock object
Account(String id, long balance) { this.id = id; this.balance = balance; }
boolean withdraw(long amount) {
synchronized (lock) { // check-then-act must be ONE atomic step
if (amount > balance) return false;
balance -= amount;
return true;
}
}
long balance() { synchronized (lock) { return balance; } }
}
public static void main(String[] args) throws InterruptedException {
Account acc = new Account("SB-1", 10_000);
int[] approved = new int[1];
Object counterLock = new Object();
Runnable atm = () -> {
for (int i = 0; i < 100; i++) {
if (acc.withdraw(70)) synchronized (counterLock) { approved[0]++; }
}
};
Thread a = new Thread(atm), b = new Thread(atm), c = new Thread(atm);
a.start(); b.start(); c.start();
a.join(); b.join(); c.join();
System.out.println("approved " + approved[0] + ", balance " + acc.balance() + ", never negative: " + (acc.balance() >= 0));
}
}
approved 142, balance 60, never negative: true
wait, notify and notifyAll
Threads can coordinate through an object's monitor: wait() releases the lock and sleeps until another thread calls notify()/notifyAll() on the same object. All three must be called while holding that object's lock, and wait() must be called in a loop that re-checks the condition (because of spurious wake-ups and competing threads).
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Main {
static class BoundedBuffer {
private final Queue<Integer> items = new LinkedList<>();
private final int capacity;
BoundedBuffer(int capacity) { this.capacity = capacity; }
synchronized void put(int x) throws InterruptedException {
while (items.size() == capacity) wait(); // ALWAYS wait in a loop
items.add(x);
notifyAll(); // wake waiting consumers
}
synchronized int take() throws InterruptedException {
while (items.isEmpty()) wait();
int x = items.remove();
notifyAll(); // wake waiting producers
return x;
}
}
public static void main(String[] args) throws InterruptedException {
BoundedBuffer buf = new BoundedBuffer(2);
List<Integer> consumed = new ArrayList<>();
Thread producer = new Thread(() -> {
try { for (int i = 1; i <= 6; i++) buf.put(i * 10); buf.put(-1); } // -1 = "no more items"
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try { for (int x; (x = buf.take()) != -1; ) consumed.add(x); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start(); consumer.start();
producer.join(); consumer.join();
System.out.println("consumed in order: " + consumed);
}
}
consumed in order: [10, 20, 30, 40, 50, 60]
Common mistakes
- Calling run() instead of start().
- Sharing mutable data without synchronisation – lost updates and stale reads.
- Synchronizing on different objects (or on a new object each time) – no mutual exclusion.
- Calling wait/notify without holding the lock – IllegalMonitorStateException.
- Using if instead of while around wait().
- Swallowing InterruptedException – restore the flag or stop the task.
- Acquiring locks in different orders – deadlock.
- Thinking volatile makes count++ atomic.
- Printing from many threads and expecting a fixed order.
Key points to remember
- Create work as a Runnable; start it with start(), wait for it with join().
- Thread scheduling order is not guaranteed.
- synchronized = mutual exclusion + visibility; it locks an object's monitor.
- volatile = visibility only; use it for simple flags.
- wait/notify need the lock; always wait in a loop.
- Prevent deadlock with a consistent lock order; interrupt is a cooperative stop signal.
Frequently asked questions
Process vs thread?
A process has its own memory space; threads within a process share memory (heap) but each has its own stack.
How many threads should I create?
For CPU-bound work, about the number of cores (Runtime.getRuntime().availableProcessors()); for I/O-bound work, more – or virtual threads (Java 21). In practice use a thread pool (next topic).
Does Thread.sleep release locks?
No. sleep keeps any locks the thread holds; wait releases the lock of the object it is called on.
Where can I learn more?
Read Java Multithreading and Java Synchronization, then practise with the exercises below.