Chapter 11
Java Multithreading
5 topics · 1 sections · beginner-friendly study notes · Updated
Multithreading lets a Java program run several independent paths of execution (threads) inside one process.
This chapter explains threads, the thread lifecycle, ways to create threads, synchronization and inter-thread communication with wait, notify and notifyAll.
Modern CPUs have many cores and servers handle many requests at once.
Threads are core to Java interviews and to writing responsive applications.
Web servers handling parallel requests, background downloads, UI that stays responsive, parallel data processing, schedulers.
Multithreading in Java
Multithreading is the ability of a program to execute two or more threads concurrently within the same process. A thread is the smallest unit of execution; threads of one process share the heap and method area but each has its own stack and program counter.
In short: A thread is one worker inside your program. Multithreading means several workers sharing the same office but each doing a different task.
Think about it
Single-threaded programs waste multi-core hardware and freeze on slow I/O. Threads let work overlap. A restaurant: one chef (single thread) makes orders one by one, while several chefs (threads) prepare dishes at the same time in the same kitchen.
A process is an independent program with its own memory; threads inside a process share memory, so communication is cheap but risky.
Every Java program starts with the main thread; the JVM also runs background threads (GC, JIT compiler).
Concurrency means tasks make progress by interleaving (possibly on one core); parallelism means tasks literally run at the same time on several cores.
Benefits
better CPU use, responsiveness, simpler modelling of independent tasks.
Costs: complexity, race conditions, deadlocks and context-switch overhead.
Thread scheduling is done by the OS/JVM and is non-deterministic, so output order of unsynchronized threads can differ in every run.
Use join() to wait for a thread to finish.
Daemon threads (setDaemon(true)) do not stop the JVM from exiting.
For real applications prefer the java.
util.
concurrent executors instead of creating raw threads manually.
Key points
- Process: Running program with its own address space.
- Thread: Lightweight path of execution inside a process.
- Concurrency: Dealing with many tasks by interleaving them.
- Parallelism: Running tasks at the same instant on multiple cores.
- Context switch: CPU switching from one thread to another.
- Threads share heap; each thread has its own stack and PC register.
- Thread scheduling order is not guaranteed.
main()runs in the "main" thread; the JVM waits for all non-daemon threads.join()waits for a thread to die.
Read more
Example
CodeSplitting work between two threads:
public class MultiThreadDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("Cores: " + Runtime.getRuntime().availableProcessors());
System.out.println("Running in: " + Thread.currentThread().getName()); // main
long[] partial = new long[2];
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 500; i++) partial[0] += i;
});
Thread t2 = new Thread(() -> {
for (int i = 501; i <= 1000; i++) partial[1] += i;
});
t1.start();
t2.start();
t1.join(); // wait for both workers
t2.join();
System.out.println(partial[0]); // 125250
System.out.println(partial[1]); // 375250
System.out.println(partial[0] + partial[1]); // 500500
}
}Thread Lifecycle in Java
The lifecycle of a thread is the set of states a Thread object passes through, defined by Thread.State: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.
In short: A thread is born (NEW), starts (RUNNABLE), sometimes has to wait or sleep, and finally dies (TERMINATED).
Think about it
Knowing the states explains deadlocks, hung threads and the output of getState() questions. A bus passenger: waiting at stop (NEW), boarding and travelling (RUNNABLE), waiting for the door lock (BLOCKED), waiting for a friend (WAITING), napping for 10 minutes (TIMED_WAITING), reached destination (TERMINATED).
NEW: object created, start() not yet called.
RUNNABLE: after start(); the thread is either running or ready and waiting for CPU (Java does not separate "ready" and "running").
BLOCKED: waiting to enter a synchronized block because another thread holds the monitor.
WAITING: waiting indefinitely for another thread, entered by `Object.
wait(), Thread.
join() or LockSupport.
park()`; left through notify/notifyAll, thread end or unpark.
TIMED_WAITING: waiting for a limited time: sleep(ms), wait(ms), join(ms).
TERMINATED: run() finished normally or by an uncaught exception; a terminated thread cannot be restarted (IllegalThreadStateException).
getState() reports the current state, isAlive() is true between start and termination.
interrupt() sets the interrupt flag and wakes a sleeping/waiting thread with InterruptedException.
Calling start() twice on the same thread is illegal.
Key points
- NEW: Created but not started.
- RUNNABLE: Running or ready to run.
- BLOCKED: Waiting for a monitor lock.
- WAITING: Waiting without time limit for another thread.
- TIMED_WAITING: Waiting up to a given time (sleep, timed wait/join).
- TERMINATED: Finished execution.
Example
CodeObserving thread states:
public class LifecycleDemo {
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
});
System.out.println(t.getState()); // NEW
t.start();
Thread.sleep(100);
System.out.println(t.getState()); // TIMED_WAITING (inside sleep)
t.join();
System.out.println(t.getState()); // TERMINATED
System.out.println(t.isAlive()); // false
try {
t.start(); // cannot restart
} catch (IllegalThreadStateException e) {
System.out.println("Cannot start a thread twice");
}
// BLOCKED example
Object lock = new Object();
Thread holder = new Thread(() -> {
synchronized (lock) {
try { Thread.sleep(400); } catch (InterruptedException e) { }
}
});
Thread waiter = new Thread(() -> {
synchronized (lock) { System.out.println("waiter got the lock"); }
});
holder.start();
Thread.sleep(100); // let holder take the lock first
waiter.start();
Thread.sleep(100);
System.out.println(waiter.getState()); // BLOCKED
holder.join();
waiter.join(); // waiter got the lock
}
}start()
NEW → RUNNABLE.
Creates a new call stack and calls run().
sleep / wait / join
sleep(ms) → TIMED_WAITING keeping locks; wait() → WAITING and releases the lock; join() waits for another thread.
synchronized contention
RUNNABLE → BLOCKED while another thread owns the lock.
run() ends
RUNNABLE → TERMINATED; cannot restart.
Creating Thread in Java
A thread can be created by extending the Thread class and overriding run(), by implementing Runnable (or using a lambda) and passing it to a Thread, or by submitting Runnable/Callable tasks to an ExecutorService. A thread begins only when start() is called.
In short: Write the job in run(), hand it to a Thread, and call start(). Never call run() yourself.
Think about it
Choosing Runnable/Callable with executors is the standard, flexible and scalable way to run tasks. Writing a job card (Runnable) and giving it to a worker (Thread) who starts it on the shop floor.
Approach 1: `class MyThread extends Thread { public void run() {...
} }` — uses up your single inheritance.
Approach 2: `class Task implements Runnable and new Thread(task).
start()` — preferred because the class can still extend another class and the task can be reused by executors.
Approach 3: lambda `new Thread(() -> ...
)` since Runnable is a functional interface.
Approach 4: `ExecutorService pool = Executors.
newFixedThreadPool(n); Future<T> f = pool.
submit(callable);` — Callable returns a value and can throw checked exceptions; `future.
get()` blocks until the result is ready.
Always shutdown() the pool.
start() creates a new call stack and runs run() in the new thread; calling run() directly is a plain method call on the current thread.
Useful API: setName/getName, setPriority (1–10, only a hint), setDaemon, sleep, yield, join, interrupt, isInterrupted, Thread.
currentThread().
Key points
- Runnable: Functional interface with void
run(). - Callable: Like Runnable but
call()returns a value and may throw. - Future: Handle to a result that will be available later.
- ExecutorService: Thread pool that runs submitted tasks.
- Daemon thread: Background thread that does not keep the JVM alive.
start()= new thread;run()= normal call on the current thread.- Runnable preferred over extending Thread.
- Callable returns a value; Runnable does not.
- Always shut down executors.
Example
CodeFour ways to run code in a thread:
import java.util.concurrent.*;
public class CreateThreads {
static class Worker extends Thread { // way 1
public void run() {
System.out.println("Worker thread: " + getName());
}
}
static class Task implements Runnable { // way 2
public void run() {
System.out.println("Runnable in: " + Thread.currentThread().getName());
}
}
public static void main(String[] args) throws Exception {
Worker w = new Worker();
w.setName("W-1");
w.start();
w.join(); // Worker thread: W-1
Thread t = new Thread(new Task(), "T-2");
t.start();
t.join(); // Runnable in: T-2
Thread lam = new Thread(() -> // way 3: lambda
System.out.println("Lambda in: " + Thread.currentThread().getName()), "L-3");
lam.start();
lam.join(); // Lambda in: L-3
new Task().run(); // Runnable in: main (no new thread!)
ExecutorService pool = Executors.newFixedThreadPool(2); // way 4
Callable<Integer> square = () -> 7 * 7;
Future<Integer> result = pool.submit(square);
System.out.println(result.get()); // 49
pool.shutdown();
}
}Synchronization in Java
Synchronization is the technique of controlling access of multiple threads to shared resources so that only one thread at a time executes a critical section. In Java it is done with the synchronized keyword (methods and blocks), which uses the intrinsic lock (monitor) of an object.
In short: A synchronized block is a room with one key. Only the thread holding the key can enter; the others wait outside.
Think about it
Without it shared data gets corrupted in ways that are hard to reproduce. It is the heart of thread-safety questions. A bank counter with one teller window: customers (threads) queue so that two people do not update the same account at the same moment.
A race condition occurs when threads read-modify-write shared data without coordination: count++ is three steps (read, add, write) so two threads can overwrite each other, giving a total less than expected.
A `synchronized` instance method locks this; a `static synchronized` method locks the Class object; a block `synchronized (obj) { ...
}` locks the given object and is preferred because it keeps the critical section small.
Locks are reentrant (a thread already holding a lock can enter again).
Synchronization gives mutual exclusion AND visibility (changes made inside are visible to the next thread acquiring the same lock).
volatile gives visibility and ordering for a single variable but NOT atomicity for compound actions.
For simple counters use AtomicInteger; for flexible locking use ReentrantLock.
Deadlock happens when two threads each hold a lock the other needs; avoid it by acquiring locks in a fixed global order.
Over-synchronizing hurts performance.
Key points
- Critical section: Code that accesses shared state and must not run concurrently.
- Race condition: Result depends on timing of threads.
- Monitor / intrinsic lock: Lock built into every Java object.
- volatile: Guarantees visibility of a variable, not atomic compound operations.
- Deadlock: Threads wait forever for each other locks.
- synchronized method locks this; static synchronized locks ClassName.class.
- Prefer small synchronized blocks over whole methods.
- count++ is NOT atomic; use synchronized, AtomicInteger or a Lock.
- volatile: visibility only. Locks: visibility + mutual exclusion.
Example
CodeRace condition and three ways to fix it:
import java.util.concurrent.atomic.AtomicInteger;
public class SyncDemo {
static class UnsafeCounter {
int count;
void inc() { count++; } // race condition
}
static class SafeCounter {
private int count;
synchronized void inc() { count++; } // locks 'this'
synchronized int get() { return count; }
}
static class BlockCounter {
private int count;
private final Object lock = new Object();
void inc() { synchronized (lock) { count++; } }
int get() { synchronized (lock) { return count; } }
}
static void runTwice(Runnable r) throws InterruptedException {
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start();
a.join(); b.join();
}
public static void main(String[] args) throws InterruptedException {
UnsafeCounter u = new UnsafeCounter();
runTwice(() -> { for (int i = 0; i < 100000; i++) u.inc(); });
System.out.println("Unsafe : " + u.count); // usually less than 200000
SafeCounter s = new SafeCounter();
runTwice(() -> { for (int i = 0; i < 100000; i++) s.inc(); });
System.out.println("Safe : " + s.get()); // 200000
BlockCounter b = new BlockCounter();
runTwice(() -> { for (int i = 0; i < 100000; i++) b.inc(); });
System.out.println("Block : " + b.get()); // 200000
AtomicInteger atomic = new AtomicInteger();
runTwice(() -> { for (int i = 0; i < 100000; i++) atomic.incrementAndGet(); });
System.out.println("Atomic : " + atomic.get());// 200000
}
}wait notify and notifyAll
wait(), notify() and notifyAll() are methods of java.lang.Object used for inter-thread communication. A thread calls wait() to release the lock and sleep until another thread calls notify() (wakes one waiting thread) or notifyAll() (wakes all waiting threads) on the same object. They must be called from a synchronized context.
In short: wait() means: I will sleep and give up the key until something changes. notify() means: wake one sleeper, the condition may have changed.
Think about it
Threads often need to wait for a condition (buffer not empty/not full). Busy-waiting wastes CPU; wait/notify lets them sleep efficiently. A kitchen pass: the cook waits for the counter to be free; the waiter rings a bell (notify) when it is empty.
Calling them without owning the monitor throws IllegalMonitorStateException.
wait() releases the monitor and moves the thread to the WAITING state (or TIMED_WAITING for wait(ms)); when woken it must reacquire the lock before continuing.
ALWAYS call wait() inside a `while (!
condition) loop, not an if`, because of spurious wake-ups and because another thread may have changed the condition again.
notify() picks an arbitrary single waiter, so use notifyAll() when waiters wait for different conditions (for example both producers and consumers) to avoid lost signals.
Difference from sleep(): sleep is a Thread static method, keeps the lock and wakes by time; wait is an Object method, releases the lock and wakes by notify (or timeout).
This is the basis of the producer-consumer problem and of BlockingQueue in java.
util.
concurrent, which is the easier modern alternative.
Key points
wait(): Release the lock and wait to be notified.notify(): Wake one waiting thread.notifyAll(): Wake all waiting threads; they compete for the lock.- Spurious wake-up: Waking without notify; hence the while loop.
- Producer-consumer: One side produces items, the other consumes them via a shared buffer.
- Methods of Object, not Thread; need synchronized on the same object.
- wait releases the lock; sleep does not.
- Use while(condition)
wait(); - Prefer
notifyAll()unless only one kind of waiter exists.
Read more
Example
CodeProducer-consumer with wait and notifyAll:
public class ProducerConsumer {
static class Buffer { // holds one item
private int value;
private boolean full = false;
synchronized void put(int v) throws InterruptedException {
while (full) wait(); // wait until empty
value = v;
full = true;
System.out.println("Produced " + v);
notifyAll(); // wake consumer
}
synchronized int take() throws InterruptedException {
while (!full) wait(); // wait until full
full = false;
System.out.println("Consumed " + value);
notifyAll(); // wake producer
return value;
}
}
public static void main(String[] args) throws InterruptedException {
Buffer buf = new Buffer();
Thread producer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) buf.put(i); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) buf.take(); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start();
consumer.start();
producer.join();
consumer.join();
// Produced 1, Consumed 1, Produced 2, Consumed 2, Produced 3, Consumed 3
}
}Solved examples
What is the difference between t.start() and t.run()?
Explanation
Formula Applied:—Approach note: Calling start() twice throws IllegalThreadStateException.
Name the thread state after start() when the thread calls Thread.sleep(1000).
Thread state
Formula Applied:—Approach note: wait() with no argument gives WAITING; synchronized contention gives BLOCKED.
Two threads each execute count++ 1000 times on a shared int. Why can the final value be less than 2000, and how do you fix it?
Cause and fix
Formula Applied:—Approach note: volatile alone does not fix it, because the increment is still not atomic.
Why must wait() be inside a while loop?
Reason
Formula Applied:—Approach note: Write it as a standard pattern and never use if.
Real-world applications
Using Java Multithreading in real projects
Web servers handling parallel requests, background downloads, UI that stays responsive, parallel data processing, schedulers.
Common mistakes
❌ Myth: Calling run() starts a new thread.
Why this is wrong: run() is just a method; only start() creates a thread.
✅ Verified Truth: Always call start().
⚠️ Exam Tip: Output-order questions test this.
❌ Myth: sleep() releases the lock.
Why this is wrong: sleep keeps all monitors it holds.
✅ Verified Truth: wait() releases the lock; sleep() does not.
⚠️ Exam Tip: Say: sleep = Thread, wait = Object.
❌ Myth: volatile makes count++ thread-safe.
Why this is wrong: count++ is a compound read-modify-write.
✅ Verified Truth: Use synchronized or AtomicInteger.
⚠️ Exam Tip: volatile = visibility only.
❌ Myth: Thread priority guarantees execution order.
Why this is wrong: Priority is only a hint to the scheduler.
✅ Verified Truth: Use synchronization or join for ordering.
⚠️ Exam Tip: Output of unsynchronized threads is non-deterministic.
Revision notes
Multithreading lets a Java program run several independent paths of execution (threads) inside one process. This chapter explains threads, the thread lifecycle, ways to create threads, synchronization and inter-thread communication with wait, notify and notifyAll.
High-Yield Quick Revision Points
- Threads share heap; each has its own stack
- States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
- start() creates a thread; run() is a normal call; no restart
- Runnable preferred; Callable + Future for results; shutdown executors
- synchronized = mutual exclusion + visibility; count++ is not atomic
- wait/notify/notifyAll: in synchronized, with while loop; wait releases lock
Practice questions
Which method starts a new thread?
Which is NOT a state in Thread.State?
wait() must be called from:
Which interface can return a value from a task?
Which statement about sleep() is true?
What does static synchronized lock?