Advanced Java
Multithreading
Complete lesson for Multithreading using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Multithreading
Section: Advanced Java. Run many tasks at the same time: threads, Runnable, thread life cycle, synchronization, wait/notify, deadlock, executors, and concurrent utilities — with real-life examples.
What is multithreading?
- A thread is a small, independent path of execution inside a program. Multithreading means running two or more threads at the same time.
- Every Java program starts with one thread, called
main. You can create more threads to do work in parallel. - Threads of one program share the same memory (objects on the heap), which makes communication fast but needs care.
- Real life: a restaurant kitchen. One chef makes rice, another fries starters, another prepares dessert. The meal is ready much faster than with one chef doing everything.
- Benefits: better CPU use on multi-core machines, responsive apps (the screen does not freeze during a download), and faster servers that handle many users at once.
public class Kitchen {
static void cook(String chef, String dish) {
for (int step = 1; step <= 3; step++) {
System.out.println(chef + " - " + dish + " step " + step);
try {
Thread.sleep(100); // pretend each step takes time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread chef1 = new Thread(() -> cook("Chef Asha", "Biryani"));
Thread chef2 = new Thread(() -> cook("Chef Ravi", "Paneer Tikka"));
chef1.start(); // both chefs work at the same time
chef2.start();
chef1.join(); // main waits for both to finish
chef2.join();
System.out.println("Meal ready! (output lines interleave: true parallel work)");
}
} Real-life examples of multithreading
| Application | What the threads do at the same time |
|---|---|
| One thread shows the chat screen, one receives messages, one uploads a photo | |
| Web browser | Each tab loads pages, plays video, and runs scripts independently |
| Video game | Graphics, sound, player input, and network updates run in parallel |
| Music app | Plays the current song while downloading the next one |
| MS Word / Google Docs | You type while spell-check and autosave run in the background |
| Banking server | Each customer request (balance, transfer, statement) runs on its own thread |
| Ola / Uber | GPS location updates, ride matching, and fare calculation run together |
| Railway reservation | Many counters book tickets on the same train at once (needs synchronization) |
| Toll plaza | Several booths serve vehicles in parallel, like a thread pool |
| IDE (IntelliJ, VS Code) | Editor, compiler, indexer, and error checker run on different threads |
Differences between process and thread
- A process is a running program (for example, Chrome or a Java application). A thread is a unit of work inside a process.
- Real life: a company is a process with its own office and resources; employees are threads working inside it and sharing the office.
| Point | Process | Thread |
|---|---|---|
| Meaning | A program in execution | A path of execution inside a process |
| Memory | Own separate memory space | Shares heap memory with other threads of the process |
| Own stack? | Yes (for its threads) | Yes, each thread has its own stack |
| Creation cost | Heavy (slow to create) | Light (fast to create) |
| Communication | Slow: pipes, sockets, files | Fast: shared objects |
| Context switch | Expensive | Cheaper |
| Failure impact | One process crash does not affect others | An uncaught error can affect the whole process |
| Java example | Running java App starts a JVM process | new Thread(task).start() inside that JVM |
| Real life | A company | Employees of the company |
Creating a thread by extending Thread
- Write a class that extends
Threadand overriderun()with the work to do. - Create an object and call
start(). The JVM creates a new thread that callsrun(). - Drawback: Java allows only one superclass, so your class cannot extend anything else.
class DownloadThread extends Thread {
private final String file;
DownloadThread(String file) {
super("downloader-" + file); // thread name
this.file = file;
}
@Override
public void run() {
for (int p = 25; p <= 100; p += 25) {
System.out.println(getName() + ": " + file + " " + p + "%");
}
}
}
public class ExtendThreadDemo {
public static void main(String[] args) {
new DownloadThread("movie.mp4").start();
new DownloadThread("song.mp3").start();
System.out.println("main keeps running while files download");
}
} Creating a thread by implementing Runnable
- Write the task in a class that implements
Runnable(or as a lambda, becauseRunnablehas one method). - Pass the task to a
Threadand callstart(). The task is separate from the worker that runs it. - Preferred approach: your class can still extend another class, and the same task can run on a thread pool.
class PrintBill implements Runnable {
private final String table;
PrintBill(String table) {
this.table = table;
}
@Override
public void run() {
System.out.println("Printing bill for " + table + " on " + Thread.currentThread().getName());
}
}
public class RunnableDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintBill("Table 4"), "printer-1"); // Runnable class
Thread t2 = new Thread(() -> // Runnable lambda
System.out.println("Sending order to kitchen on " + Thread.currentThread().getName()),
"kitchen-1");
t1.start();
t2.start();
}
} Differences between extending Thread and implementing Runnable
| Point | extends Thread | implements Runnable |
|---|---|---|
| Inheritance | Uses your one allowed superclass | Class can still extend another class |
| Design | Task and worker are mixed together | Task is separate from the thread that runs it |
| Reuse | One object = one thread | One task can run on many threads or a pool |
| Lambda support | No | Yes: new Thread(() -> work()) |
| Thread pools | Awkward | Natural: executor.submit(task) |
| Return a result | No | No (use Callable<V> for results) |
| Recommended? | Rarely | Yes |
start() vs run()
start()creates a new thread, moves it to RUNNABLE, and that new thread callsrun().- Calling
run()directly is just a normal method call on the current thread. No new thread is created. - Calling
start()twice on the same thread throwsIllegalThreadStateException.
| Point | start() | run() called directly |
|---|---|---|
| New thread created? | Yes | No |
| Runs on | The new thread | The current thread (for example main) |
| Parallel execution | Yes | No, it runs sequentially |
| Can be called twice? | No: IllegalThreadStateException | Yes, like any method |
public class StartVsRun {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Running on: " + Thread.currentThread().getName());
Thread t = new Thread(task, "worker");
t.run(); // Running on: main (no new thread)
t.start(); // Running on: worker (new thread)
// t.start(); // IllegalThreadStateException: a thread can start only once
}
} Thread life cycle
- Every thread passes through states defined in the enum
Thread.State. Check the current state witht.getState(). - A thread moves between RUNNABLE and the three waiting states many times, but NEW and TERMINATED happen only once.
- RUNNABLE covers both "ready" (waiting for the CPU) and "running" (on the CPU). The scheduler switches between them.
| State | Meaning | How a thread enters it | Real life: a chef |
|---|---|---|---|
| NEW | Created but not started | new Thread(task) | Chef hired, not yet in the kitchen |
| RUNNABLE | Ready or running on the CPU | start(), or returning from a waiting state | Chef is cooking (or ready to cook) |
| BLOCKED | Waiting to enter a synchronized block held by another thread | Trying to get a monitor lock | Waiting for the only stove to be free |
| WAITING | Waiting with no time limit for another thread | wait(), join(), LockSupport.park() | Waiting for the next order, however long it takes |
| TIMED_WAITING | Waiting for a fixed time | sleep(ms), wait(ms), join(ms) | Oven timer set for 10 minutes |
| TERMINATED | Finished; cannot be restarted | run() ends normally or with an exception | Shift over, chef goes home |
public class LifeCycleDemo {
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Object stove = new Object();
Thread sleeper = new Thread(() -> pause(500));
System.out.println("1. " + sleeper.getState()); // NEW
sleeper.start();
pause(100);
System.out.println("2. " + sleeper.getState()); // TIMED_WAITING (sleeping)
Thread waiter = new Thread(() -> {
synchronized (stove) {
try {
stove.wait(); // waits for notify
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
waiter.start();
pause(100);
System.out.println("3. " + waiter.getState()); // WAITING
Thread blocked;
synchronized (stove) { // main holds the lock
blocked = new Thread(() -> { synchronized (stove) { } });
blocked.start();
pause(100);
System.out.println("4. " + blocked.getState()); // BLOCKED
stove.notifyAll(); // wake the waiter
}
sleeper.join();
waiter.join();
blocked.join();
System.out.println("5. " + sleeper.getState()); // TERMINATED
}
} Java thread life cycle — 6 thread states
A thread is NEW when created, becomes RUNNABLE after start(),
may pause in BLOCKED, WAITING, or TIMED_WAITING, and ends in
TERMINATED when run() finishes. Think of a chef: hired, cooking, waiting for the stove,
waiting for an order, watching the oven timer, and finally going home.
- NEW → RUNNABLE: only through
start(), and only once. - BLOCKED: waiting to enter a
synchronizedblock another thread holds. - WAITING / TIMED_WAITING:
wait(),join(),sleep(ms)— returns to RUNNABLE when signalled or time is over. - TERMINATED:
run()has ended; the thread cannot be restarted.
Important Thread methods
| Method | What it does | Example |
|---|---|---|
start() | Starts a new thread that calls run() | t.start(); |
run() | Contains the task code | Overridden or passed as a Runnable |
Thread.sleep(ms) | Pauses the current thread; keeps any locks it holds | Thread.sleep(1000); |
join() | Current thread waits until the other thread finishes | t.join(); |
Thread.yield() | Hints that the current thread can give up the CPU | Rarely needed |
interrupt() | Asks a thread to stop; wakes it from sleep or wait | t.interrupt(); |
isInterrupted() | Checks the interrupt flag | while (!isInterrupted()) |
isAlive() | True if started and not yet terminated | t.isAlive() |
getName() / setName() | Thread name for logs | new Thread(task, "worker-1") |
setPriority(n) | Hint from 1 (MIN) to 10 (MAX); default 5 | t.setPriority(Thread.MAX_PRIORITY); |
setDaemon(true) | Makes a background thread; call before start() | Autosave, cleanup |
Thread.currentThread() | Returns the thread running this code | Thread.currentThread().getName() |
getState() | Returns the current Thread.State | t.getState() |
sleep() and join()
sleep(ms)pauses the current thread for the given time. It throws the checkedInterruptedException.join()makes the current thread wait until another thread finishes.join(ms)waits at most that long.- Real life:
sleepis setting a 5-minute alarm for a nap;joinis waiting at the door until your friend finishes getting ready.
public class FamilyTrip {
public static void main(String[] args) throws InterruptedException {
Thread getReady = new Thread(() -> {
String[] steps = { "bath", "dress up", "pack bag" };
for (String s : steps) {
System.out.println("Friend: " + s);
try {
Thread.sleep(200); // each step takes time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
});
getReady.start();
System.out.println("You: waiting at the door...");
getReady.join(); // wait until the friend is ready
System.out.println("You: let us go!");
}
} Thread priorities
- Each thread has a priority from 1 to 10. The default is 5 (inherited from the creating thread).
- Priority is only a hint to the operating system scheduler. Never rely on it for correctness.
- Real life: an ambulance siren asks other vehicles to give way, but traffic does not always clear immediately.
| Constant | Value | Meaning |
|---|---|---|
Thread.MIN_PRIORITY | 1 | Lowest priority hint |
Thread.NORM_PRIORITY | 5 | Default |
Thread.MAX_PRIORITY | 10 | Highest priority hint |
Daemon threads
- A daemon thread is a background helper. The JVM exits when only daemon threads are left; it does not wait for them.
- Mark a thread as daemon with
setDaemon(true)beforestart(). The garbage collector runs on daemon threads. - Do not use daemon threads for work that must finish, such as saving files, because they can stop at any moment.
- Real life: background music in a shop. When the shop closes (all customers leave), the music simply stops.
public class DaemonDemo {
public static void main(String[] args) throws InterruptedException {
Thread music = new Thread(() -> {
while (true) {
System.out.println("background music playing...");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
return;
}
}
});
music.setDaemon(true); // background helper
music.start();
System.out.println("Customers shopping");
Thread.sleep(500);
System.out.println("Shop closed: main ends, daemon music stops automatically");
}
} Race condition and synchronized
- A race condition happens when two threads read and change shared data at the same time, and the result depends on timing.
- Real life: two passengers at different counters both see "1 seat left" and both pay for the same seat.
synchronizedlets only one thread at a time run the code for a given lock (monitor). Others wait in BLOCKED state.- A
synchronizedinstance method locksthis; asynchronized staticmethod locks theClassobject; asynchronized (obj)block locksobj. - Synchronization also guarantees visibility: changes made inside are seen by the next thread that takes the same lock.
class TrainCounter {
private int seatsLeft = 1;
// Remove "synchronized" and both passengers may book the last seat
synchronized void book(String passenger) {
if (seatsLeft > 0) {
pause(50); // slow payment makes the race visible
seatsLeft--;
System.out.println(passenger + " booked the last seat");
} else {
System.out.println(passenger + ": sorry, train is full");
}
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class RaceDemo {
public static void main(String[] args) throws InterruptedException {
TrainCounter counter = new TrainCounter();
Thread asha = new Thread(() -> counter.book("Asha"));
Thread ravi = new Thread(() -> counter.book("Ravi"));
asha.start();
ravi.start();
asha.join();
ravi.join();
// With synchronized: exactly one booking and one "train is full"
}
} Differences between synchronized method and synchronized block
| Point | synchronized method | synchronized block |
|---|---|---|
| Syntax | synchronized void book() { } | synchronized (lock) { ... } |
| Lock used | this (or the Class for static methods) | Any object you choose |
| Scope | Whole method | Only the critical lines |
| Performance | Holds the lock longer | Shorter lock time, better concurrency |
| Control | Less | More: can use a private lock object |
| Best for | Small methods that are fully critical | Methods where only a few lines touch shared data |
public class Wallet {
private final Object lock = new Object(); // private lock: outsiders cannot block it
private double balance = 1000;
void pay(String item, double amount) {
System.out.println("Checking offers for " + item); // no lock needed here
synchronized (lock) { // only the critical part
if (amount <= balance) {
balance -= amount;
System.out.println("Paid " + amount + " for " + item + ", balance " + balance);
} else {
System.out.println("Insufficient balance for " + item);
}
}
}
public static void main(String[] args) {
Wallet w = new Wallet();
new Thread(() -> w.pay("Movie ticket", 700)).start();
new Thread(() -> w.pay("Dinner", 600)).start();
}
} Inter-thread communication: wait(), notify(), notifyAll()
- Threads can signal each other using the methods of
Object:wait()releases the lock and sleeps until notified;notify()wakes one waiting thread;notifyAll()wakes all of them. - They must be called inside a
synchronizedblock on the same object, otherwiseIllegalMonitorStateExceptionis thrown. - Always call
wait()inside awhileloop that re-checks the condition, because a thread can wake up spuriously. - Real life: a chef and a waiter share one serving counter. The chef waits if the counter is full; the waiter waits if it is empty; each calls the other when the counter changes.
class ServingCounter {
private String dish; // null = counter empty
synchronized void put(String d) throws InterruptedException {
while (dish != null) {
wait(); // chef waits until the waiter takes the dish
}
dish = d;
System.out.println("Chef placed: " + d);
notifyAll(); // tell the waiter
}
synchronized String take() throws InterruptedException {
while (dish == null) {
wait(); // waiter waits until a dish is ready
}
String d = dish;
dish = null;
System.out.println("Waiter served: " + d);
notifyAll(); // tell the chef
return d;
}
}
public class Restaurant {
public static void main(String[] args) throws InterruptedException {
ServingCounter counter = new ServingCounter();
String[] menu = { "Biryani", "Dosa", "Paneer Tikka" };
Thread chef = new Thread(() -> {
try {
for (String d : menu) counter.put(d);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread waiter = new Thread(() -> {
try {
for (int i = 0; i < menu.length; i++) counter.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
chef.start();
waiter.start();
chef.join();
waiter.join();
}
}
// Output alternates: Chef placed / Waiter served for each dish Differences between sleep() and wait()
| Point | sleep() | wait() |
|---|---|---|
| Class | Thread (static method) | Object (instance method) |
| Releases the lock? | No, keeps all locks | Yes, releases the monitor of that object |
| Needs synchronized? | No | Yes, otherwise IllegalMonitorStateException |
| Wakes up when | Time is over or interrupted | notify() / notifyAll(), time over (if given), or interrupted |
| State while paused | TIMED_WAITING | WAITING (or TIMED_WAITING with a timeout) |
| Purpose | Pause for a while | Wait for a condition signalled by another thread |
| Real life | Taking a 10-minute nap | Waiting at the counter until your order number is called |
Advanced — Multithreading
Deadlock and how to avoid it
- A deadlock happens when two or more threads each hold a lock and wait forever for a lock held by the other.
- Real life: two cars meet on a narrow one-lane bridge from opposite sides. Neither can move forward, and neither will reverse.
- Four conditions together cause deadlock: mutual exclusion, hold and wait, no preemption, and circular wait. Break any one to prevent it.
- Practical fixes: always take locks in the same global order, hold locks for as short a time as possible, or use
tryLockwith a timeout.
public class DeadlockFix {
private static final Object pen = new Object();
private static final Object paper = new Object();
// DEADLOCK (do not do this): student A locks pen then paper,
// student B locks paper then pen. Each holds one and waits forever for the other.
static void writeExam(String student) {
synchronized (pen) { // FIX: every thread locks pen first, then paper
pause(50);
synchronized (paper) {
System.out.println(student + " is writing the exam");
}
}
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> writeExam("Asha"));
Thread b = new Thread(() -> writeExam("Ravi"));
a.start();
b.start();
a.join();
b.join();
System.out.println("No deadlock: consistent lock order");
}
} volatile: visibility between threads
- Each CPU core may cache variables. Without synchronization, one thread may never see another thread updating a field.
volatileguarantees that every read sees the latest write, and prevents reordering around it.volatiledoes NOT make compound actions likecount++atomic. Use it for simple flags; use atomics or locks for counters.
public class VolatileFlag {
private static volatile boolean running = true; // without volatile the worker may loop forever
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) {
loops++;
}
System.out.println("Worker stopped after " + loops + " loops");
});
worker.start();
Thread.sleep(200);
running = false; // the worker sees this change
worker.join();
}
} Atomic variables
java.util.concurrent.atomicclasses (AtomicInteger,AtomicLong,AtomicBoolean,AtomicReference) update values atomically without locks.- They use hardware compare-and-set (CAS) instructions, so they are fast for counters and flags.
- Real life: a like counter on a viral video where thousands of people tap "like" at the same moment.
import java.util.concurrent.atomic.AtomicInteger;
public class LikeCounter {
private static int unsafeLikes = 0;
private static final AtomicInteger likes = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable fans = () -> {
for (int i = 0; i < 10_000; i++) {
unsafeLikes++; // read-modify-write race
likes.incrementAndGet(); // atomic
}
};
Thread t1 = new Thread(fans);
Thread t2 = new Thread(fans);
Thread t3 = new Thread(fans);
t1.start(); t2.start(); t3.start();
t1.join(); t2.join(); t3.join();
System.out.println("unsafe likes = " + unsafeLikes); // usually less than 30000
System.out.println("atomic likes = " + likes.get()); // always 30000
}
} ExecutorService and thread pools
- Creating a new thread for every task is expensive. A thread pool keeps a fixed set of worker threads and feeds them tasks from a queue.
- Real life: a bank with 3 cashier counters and a token queue. Customers (tasks) wait for the next free cashier (thread).
- Common pools:
Executors.newFixedThreadPool(n),newCachedThreadPool(),newSingleThreadExecutor(),newScheduledThreadPool(n). - Always shut the pool down with
shutdown()(or try-with-resources on Java 19+), otherwise the JVM may not exit.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BankCounters {
public static void main(String[] args) throws InterruptedException {
ExecutorService cashiers = Executors.newFixedThreadPool(3); // 3 counters
for (int token = 1; token <= 8; token++) { // 8 customers in the queue
int t = token;
cashiers.submit(() -> {
System.out.println("Token " + t + " served by " + Thread.currentThread().getName());
pause(200);
});
}
cashiers.shutdown(); // no new customers
cashiers.awaitTermination(5, TimeUnit.SECONDS); // finish the queue
System.out.println("Bank closed");
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} Callable and Future: tasks that return results
Runnable.run()returns nothing and cannot throw checked exceptions.Callable<V>.call()returns a value and can throw.- Submitting a
Callablereturns aFuture<V>.future.get()waits for the result. - Real life: you ask three shops for a laptop price at the same time and take the lowest quote when all reply.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PriceCheck {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
List<Callable<Integer>> shops = List.of(
() -> { Thread.sleep(300); return 54999; }, // shop A
() -> { Thread.sleep(100); return 52999; }, // shop B
() -> { Thread.sleep(200); return 53499; } // shop C
);
List<Future<Integer>> quotes = pool.invokeAll(shops); // all shops asked in parallel
int best = Integer.MAX_VALUE;
for (Future<Integer> f : quotes) {
best = Math.min(best, f.get()); // get() waits for the result
}
System.out.println("Best price: Rs." + best); // 52999
pool.shutdown();
}
} CompletableFuture: asynchronous pipelines
CompletableFuture(Java 8) runs tasks asynchronously and chains the next steps without blocking.- Useful methods:
supplyAsync,thenApply,thenCombine,thenAccept,exceptionally,allOf,join. - Real life: while the chef cooks, the cashier calculates GST; the bill combines both when ready.
import java.util.concurrent.CompletableFuture;
public class OrderPipeline {
static int fetchPrice() { pause(200); return 1000; }
static double fetchTaxRate() { pause(150); return 0.18; }
public static void main(String[] args) {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(OrderPipeline::fetchPrice);
CompletableFuture<Double> tax = CompletableFuture.supplyAsync(OrderPipeline::fetchTaxRate);
double total = price.thenCombine(tax, (p, t) -> p + p * t) // both run in parallel
.thenApply(v -> Math.round(v * 100) / 100.0)
.exceptionally(ex -> -1.0) // fallback on failure
.join();
System.out.println("Total with GST: Rs." + total); // 1180.0
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} Concurrent collections
- Normal collections such as
ArrayListandHashMapare not thread-safe. Use the concurrent versions for shared data.
| Collection | Use it for | Real life |
|---|---|---|
ConcurrentHashMap | Shared map with many readers and writers; atomic merge and compute | Live vote counts per candidate |
CopyOnWriteArrayList | Lists that are read often and changed rarely | List of event listeners |
ArrayBlockingQueue / LinkedBlockingQueue | Producer-consumer: put waits when full, take waits when empty | Bakery shelf between baker and customers |
ConcurrentLinkedQueue | Non-blocking queue for high throughput | Log messages from many threads |
ConcurrentSkipListMap | Sorted concurrent map | Live leaderboard |
Synchronizers: CountDownLatch and Semaphore
CountDownLatch(n): one or more threads wait until n events have happened. Real life: the umpire starts the match only when all players are ready.Semaphore(n): allows at most n threads into a section at once. Real life: a parking lot with only 2 slots.CyclicBarriermakes a group of threads wait for each other at a meeting point, again and again.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class Synchronizers {
static final Semaphore parkingSlots = new Semaphore(2); // only 2 cars at a time
static void park(String car) {
try {
parkingSlots.acquire(); // wait for a free slot
try {
System.out.println(car + " parked");
Thread.sleep(200);
} finally {
System.out.println(car + " left");
parkingSlots.release();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
String[] players = { "Asha", "Ravi", "Kiran" };
CountDownLatch ready = new CountDownLatch(players.length);
for (String p : players) {
new Thread(() -> {
System.out.println(p + " is ready");
ready.countDown();
}).start();
}
ready.await(); // umpire waits for all players
System.out.println("Umpire: Play!");
for (String car : new String[] { "Car-1", "Car-2", "Car-3", "Car-4" }) {
new Thread(() -> park(car)).start(); // at most 2 parked at once
}
}
} ReentrantLock vs synchronized
| Point | synchronized | ReentrantLock |
|---|---|---|
| Syntax | Keyword on a method or block | lock.lock() ... finally { lock.unlock(); } |
| Release | Automatic at the end of the block | Manual: always unlock in finally |
| Try without waiting | No | Yes: tryLock() or tryLock(time, unit) |
| Interruptible waiting | No | Yes: lockInterruptibly() |
| Fairness option | No | Yes: new ReentrantLock(true) |
| Multiple conditions | One wait set per object | Many Condition objects |
| Use when | Simple mutual exclusion (most cases) | You need timeouts, fairness, or several conditions |
Virtual threads (Java 21)
- Platform threads map one-to-one to operating system threads and are expensive, so apps usually have hundreds of them.
- Virtual threads are lightweight threads managed by the JVM. You can create millions; blocking calls like
sleepor I/O park them cheaply. - Best for many concurrent blocking tasks such as web requests and database calls. They do not make CPU-heavy work faster.
- Real life: instead of hiring a full-time employee for each customer call, a call centre uses a smart system where agents handle the next caller whenever one is on hold.
| Point | Platform thread | Virtual thread |
|---|---|---|
| Managed by | Operating system | JVM |
| Cost | About 1 MB stack, slow to create | Very small, fast to create |
| How many | Thousands at most | Millions |
| Blocking | Wastes an OS thread | Cheap: the carrier thread is freed |
| Create | new Thread(task) | Thread.ofVirtual().start(task) |
| Pooling | Use thread pools | Do not pool; one per task |
import java.util.concurrent.Executors;
public class VirtualThreadsDemo {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { // Java 21
for (int i = 1; i <= 10_000; i++) {
int id = i;
executor.submit(() -> {
Thread.sleep(100); // blocking is cheap on virtual threads
return id;
});
}
} // close() waits for all tasks
System.out.println("10,000 tasks done in about "
+ (System.currentTimeMillis() - start) + " ms");
}
} Multithreading best practices
| Do | Do not |
|---|---|
Prefer ExecutorService over creating raw threads | Create a new thread for every small task |
| Share as little mutable data as possible; use immutable objects | Let many threads change plain fields without locks |
| Use concurrent collections and atomic classes | Share HashMap or ArrayList across threads |
| Keep synchronized sections short | Call slow I/O while holding a lock |
| Take locks in a consistent order | Nest locks in different orders in different methods |
Handle InterruptedException (restore the flag) | Swallow interrupts with an empty catch |
| Name your threads for readable logs | Leave every thread as Thread-0, Thread-1 |
| Shut down pools when done | Use deprecated stop(), suspend(), resume() |
Tricky Interview Points
Q1) What is multithreading?
Answer Running two or more threads at the same time within one program. Threads share the process memory, so work like downloading and updating the screen can happen in parallel.
Q2) Give a real-life example of multithreading.
Answer A restaurant kitchen with several chefs cooking different dishes at once, or a music app that plays a song while downloading the next one.
Q3) What is the difference between a process and a thread?
Answer A process is a running program with its own memory. A thread is a path of execution inside a process; threads share the heap but each has its own stack, so they are lighter and communicate faster.
Q4) What are the ways to create a thread in Java?
Answer Extend Thread and override run(), implement Runnable (or use a lambda) and pass it to a Thread, implement Callable and submit it to an ExecutorService, or use virtual threads in Java 21.
Q5) Which is better: extending Thread or implementing Runnable?
Answer Implementing Runnable. It keeps your one superclass free, separates the task from the thread, works with lambdas, and can be submitted to thread pools.
Q6) What is the difference between start() and run()?
Answer start() creates a new thread that then calls run(). Calling run() directly executes it on the current thread like a normal method.
Q7) Can we start a thread twice?
Answer No. Calling start() a second time throws IllegalThreadStateException. A TERMINATED thread cannot be restarted; create a new Thread object.
Q8) Explain the thread life cycle.
Answer NEW after creation, RUNNABLE after start(), then possibly BLOCKED (waiting for a lock), WAITING (wait or join without timeout), or TIMED_WAITING (sleep or wait with timeout), and finally TERMINATED when run() ends.
Q9) What is the difference between BLOCKED and WAITING?
Answer BLOCKED means waiting to acquire a monitor lock for a synchronized block. WAITING means the thread voluntarily waits for another thread, for example with wait() or join().
Q10) What is the difference between sleep() and wait()?
Answer sleep() is a static Thread method that pauses without releasing locks. wait() is an Object method called inside synchronized code; it releases the lock and waits for notify(), notifyAll(), or a timeout.
Q11) What does join() do?
Answer It makes the current thread wait until the thread on which join() is called finishes, optionally with a timeout.
Q12) What is a daemon thread?
Answer A background service thread. The JVM exits when only daemon threads remain. Set it with setDaemon(true) before start(). The garbage collector is an example.
Q13) What is a race condition?
Answer A bug where the result depends on the timing of threads accessing shared data, for example two counters both booking the last train seat.
Q14) What is synchronization?
Answer Controlling access so only one thread at a time runs a critical section for a given lock. In Java, synchronized methods or blocks acquire an object monitor and also ensure memory visibility.
Q15) What is the difference between a synchronized method and a synchronized block?
Answer A synchronized method locks the whole method on this (or the Class for static). A block locks only selected lines on any chosen object, which reduces contention.
Q16) Why must wait() and notify() be called inside synchronized code?
Answer Because they operate on the monitor of the object. Calling them without owning the monitor throws IllegalMonitorStateException.
Q17) What is a deadlock and how can you prevent it?
Answer Two or more threads waiting forever for locks held by each other. Prevent it by acquiring locks in a fixed order, keeping lock scopes small, or using tryLock with timeouts.
Q18) What is the volatile keyword?
Answer It guarantees visibility of the latest write to a field across threads and prevents reordering. It does not make compound operations like count++ atomic.
Q19) What is the difference between Runnable and Callable?
Answer Runnable.run() returns void and cannot throw checked exceptions. Callable.call() returns a value and can throw; submitting it gives a Future.
Q20) Why use a thread pool?
Answer Reusing a fixed set of threads avoids the cost of creating threads for every task, limits resource usage, and provides queuing and lifecycle management through ExecutorService.
Q21) What is the difference between HashMap and ConcurrentHashMap?
Answer HashMap is not thread-safe. ConcurrentHashMap supports safe concurrent reads and writes with fine-grained locking, offers atomic merge and compute, and does not allow null keys or values.
Q22) What are virtual threads?
Answer Lightweight threads managed by the JVM (Java 21). Millions can run because blocking operations park them cheaply, making them ideal for I/O-heavy concurrent tasks.
Simple Programs
Railway reservation with synchronized
class Train {
private int seats;
Train(int seats) {
this.seats = seats;
}
synchronized boolean reserve(String passenger, int count) {
if (count <= seats) {
seats -= count;
System.out.println(passenger + " booked " + count + " seat(s). Left: " + seats);
return true;
}
System.out.println(passenger + " wanted " + count + ", only " + seats + " left");
return false;
}
}
public class Reservation {
public static void main(String[] args) throws InterruptedException {
Train express = new Train(5);
String[] passengers = { "Asha", "Ravi", "Kiran", "Meena" };
int[] wants = { 2, 2, 2, 1 };
Thread[] counters = new Thread[passengers.length];
for (int i = 0; i < passengers.length; i++) {
int idx = i;
counters[i] = new Thread(() -> express.reserve(passengers[idx], wants[idx]));
counters[i].start();
}
for (Thread t : counters) {
t.join();
}
// Total booked never exceeds 5, whatever the order
}
} Bakery: producer-consumer with BlockingQueue
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Bakery {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> shelf = new ArrayBlockingQueue<>(2); // shelf holds 2 cakes
Thread baker = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
shelf.put("Cake-" + i); // waits if the shelf is full
System.out.println("Baked Cake-" + i);
}
shelf.put("CLOSED");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread customer = new Thread(() -> {
try {
while (true) {
String cake = shelf.take(); // waits if the shelf is empty
if (cake.equals("CLOSED")) break;
System.out.println(" Bought " + cake);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
baker.start();
customer.start();
baker.join();
customer.join();
System.out.println("Bakery closed");
}
} Print odd and even numbers alternately with two threads
public class OddEvenPrinter {
private int number = 1;
private final int max = 10;
synchronized void print(boolean even) {
while (number <= max) {
if ((number % 2 == 0) == even) {
System.out.println(Thread.currentThread().getName() + ": " + number);
number++;
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
notifyAll(); // let the other thread exit too
}
public static void main(String[] args) {
OddEvenPrinter printer = new OddEvenPrinter();
new Thread(() -> printer.print(false), "Odd").start();
new Thread(() -> printer.print(true), "Even").start();
}
}
// Odd: 1, Even: 2, Odd: 3, ... Even: 10 Parallel sum of daily sales with a thread pool
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ParallelSum {
public static void main(String[] args) throws Exception {
int[] sales = new int[1_000_000];
for (int i = 0; i < sales.length; i++) {
sales[i] = i % 100; // sample data
}
int parts = 4;
ExecutorService pool = Executors.newFixedThreadPool(parts);
List<Future<Long>> results = new ArrayList<>();
int chunk = sales.length / parts;
for (int p = 0; p < parts; p++) {
int from = p * chunk;
int to = (p == parts - 1) ? sales.length : from + chunk;
results.add(pool.submit(() -> { // each thread sums one part
long sum = 0;
for (int i = from; i < to; i++) sum += sales[i];
return sum;
}));
}
long total = 0;
for (Future<Long> f : results) {
total += f.get();
}
pool.shutdown();
System.out.println("Total sales = " + total); // 49500000
}
} Download manager: three files at once
public class DownloadManager {
static Thread download(String file, int parts) {
Thread t = new Thread(() -> {
for (int p = 1; p <= parts; p++) {
pause(100);
System.out.println(file + ": " + (p * 100 / parts) + "%");
}
}, file);
t.start();
return t;
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread a = download("movie.mp4", 4);
Thread b = download("song.mp3", 2);
Thread c = download("notes.pdf", 3);
a.join();
b.join();
c.join();
System.out.println("All downloads done in about "
+ (System.currentTimeMillis() - start) + " ms (not 900 ms: they ran in parallel)");
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} Text editor with a daemon autosave thread
public class Editor {
public static void main(String[] args) throws InterruptedException {
StringBuilder document = new StringBuilder();
Thread autosave = new Thread(() -> {
while (true) {
pause(250);
synchronized (document) {
System.out.println("[autosave] " + document.length() + " characters saved");
}
}
});
autosave.setDaemon(true); // JVM will not wait for it
autosave.start();
for (String word : "Java threads make apps responsive".split(" ")) {
synchronized (document) {
document.append(word).append(' ');
}
System.out.println("typed: " + word);
Thread.sleep(150);
}
System.out.println("Editor closed; daemon autosave stops automatically");
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} Live vote counting with ConcurrentHashMap
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class VoteCounter {
public static void main(String[] args) throws InterruptedException {
Map<String, Integer> votes = new ConcurrentHashMap<>();
String[] booths = {
"Asha,Ravi,Asha,Kiran",
"Ravi,Ravi,Asha",
"Kiran,Asha,Asha,Ravi"
};
ExecutorService pool = Executors.newFixedThreadPool(3); // one thread per booth
for (String booth : booths) {
pool.submit(() -> {
for (String candidate : booth.split(",")) {
votes.merge(candidate, 1, Integer::sum); // atomic update
}
});
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println(votes); // Asha=6, Ravi=4, Kiran=2 (order may vary)
}
} Problem Solving Tricks
- Remember the 6 states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
- start() creates a new thread; run() alone does not. A thread can be started only once.
- Prefer Runnable or Callable plus an ExecutorService over extends Thread.
- sleep keeps the lock; wait releases it. wait and notify need synchronized on the same object.
- Always call wait() inside a while loop that re-checks the condition.
- volatile = visibility only. For counters use AtomicInteger or synchronized.
- Avoid deadlock: take locks in the same order everywhere and keep them short.
- Name threads:
new Thread(task, "worker-1")makes logs and thread dumps readable. - Always shut down executors; use try-with-resources on Java 19+.
- For many blocking tasks on Java 21, try virtual threads:
Executors.newVirtualThreadPerTaskExecutor().
Practice Programs List
- Start two threads that print 1 to 5 with different names, and join both from main.
- Create a thread by extending Thread and another by implementing Runnable for the same task.
- Demonstrate that calling run() instead of start() keeps the code on the main thread.
- Print a thread state at each stage: NEW, TIMED_WAITING, WAITING, BLOCKED, TERMINATED.
- Simulate three file downloads in parallel and print the total time taken.
- Show a race condition with a shared counter, then fix it with synchronized and with AtomicInteger.
- Build a train reservation system where several threads book seats without overbooking.
- Implement chef and waiter communication using wait() and notifyAll().
- Rewrite the chef and waiter program using a BlockingQueue.
- Print odd and even numbers alternately using two threads.
- Write a deadlock with two locks, observe it hang, then fix it with a consistent lock order.
- Use an ExecutorService with 3 threads to serve 10 bank tokens.
- Ask three "shops" for a price using Callable and invokeAll, and print the lowest.
- Run 10,000 sleeping tasks on virtual threads (Java 21) and compare with a fixed pool of 100 threads.