Skip to main content

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.

L1

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

ApplicationWhat the threads do at the same time
WhatsAppOne thread shows the chat screen, one receives messages, one uploads a photo
Web browserEach tab loads pages, plays video, and runs scripts independently
Video gameGraphics, sound, player input, and network updates run in parallel
Music appPlays the current song while downloading the next one
MS Word / Google DocsYou type while spell-check and autosave run in the background
Banking serverEach customer request (balance, transfer, statement) runs on its own thread
Ola / UberGPS location updates, ride matching, and fare calculation run together
Railway reservationMany counters book tickets on the same train at once (needs synchronization)
Toll plazaSeveral 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.
PointProcessThread
MeaningA program in executionA path of execution inside a process
MemoryOwn separate memory spaceShares heap memory with other threads of the process
Own stack?Yes (for its threads)Yes, each thread has its own stack
Creation costHeavy (slow to create)Light (fast to create)
CommunicationSlow: pipes, sockets, filesFast: shared objects
Context switchExpensiveCheaper
Failure impactOne process crash does not affect othersAn uncaught error can affect the whole process
Java exampleRunning java App starts a JVM processnew Thread(task).start() inside that JVM
Real lifeA companyEmployees of the company

Creating a thread by extending Thread

  • Write a class that extends Thread and override run() with the work to do.
  • Create an object and call start(). The JVM creates a new thread that calls run().
  • 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, because Runnable has one method).
  • Pass the task to a Thread and call start(). 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

Pointextends Threadimplements Runnable
InheritanceUses your one allowed superclassClass can still extend another class
DesignTask and worker are mixed togetherTask is separate from the thread that runs it
ReuseOne object = one threadOne task can run on many threads or a pool
Lambda supportNoYes: new Thread(() -> work())
Thread poolsAwkwardNatural: executor.submit(task)
Return a resultNoNo (use Callable<V> for results)
Recommended?RarelyYes

start() vs run()

  • start() creates a new thread, moves it to RUNNABLE, and that new thread calls run().
  • 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 throws IllegalThreadStateException.
Pointstart()run() called directly
New thread created?YesNo
Runs onThe new threadThe current thread (for example main)
Parallel executionYesNo, it runs sequentially
Can be called twice?No: IllegalThreadStateExceptionYes, 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 with t.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.
StateMeaningHow a thread enters itReal life: a chef
NEWCreated but not startednew Thread(task)Chef hired, not yet in the kitchen
RUNNABLEReady or running on the CPUstart(), or returning from a waiting stateChef is cooking (or ready to cook)
BLOCKEDWaiting to enter a synchronized block held by another threadTrying to get a monitor lockWaiting for the only stove to be free
WAITINGWaiting with no time limit for another threadwait(), join(), LockSupport.park()Waiting for the next order, however long it takes
TIMED_WAITINGWaiting for a fixed timesleep(ms), wait(ms), join(ms)Oven timer set for 10 minutes
TERMINATEDFinished; cannot be restartedrun() ends normally or with an exceptionShift 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.

Java thread life cycle diagram: NEW goes to RUNNABLE with start(). RUNNABLE goes to BLOCKED when waiting for a lock and back when it gets the lock; to WAITING with wait() or join() and back with notify() or notifyAll(); to TIMED WAITING with sleep(ms) or wait(ms) and back when the time is over or notify() is called; and to TERMINATED when run() ends. A side card compares each state to a chef in a kitchen.
Java thread life cycle — numbered arrows show each transition; the chef card gives a real-life meaning for every state
  • NEW → RUNNABLE: only through start(), and only once.
  • BLOCKED: waiting to enter a synchronized block 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

MethodWhat it doesExample
start()Starts a new thread that calls run()t.start();
run()Contains the task codeOverridden or passed as a Runnable
Thread.sleep(ms)Pauses the current thread; keeps any locks it holdsThread.sleep(1000);
join()Current thread waits until the other thread finishest.join();
Thread.yield()Hints that the current thread can give up the CPURarely needed
interrupt()Asks a thread to stop; wakes it from sleep or waitt.interrupt();
isInterrupted()Checks the interrupt flagwhile (!isInterrupted())
isAlive()True if started and not yet terminatedt.isAlive()
getName() / setName()Thread name for logsnew Thread(task, "worker-1")
setPriority(n)Hint from 1 (MIN) to 10 (MAX); default 5t.setPriority(Thread.MAX_PRIORITY);
setDaemon(true)Makes a background thread; call before start()Autosave, cleanup
Thread.currentThread()Returns the thread running this codeThread.currentThread().getName()
getState()Returns the current Thread.Statet.getState()

sleep() and join()

  • sleep(ms) pauses the current thread for the given time. It throws the checked InterruptedException.
  • join() makes the current thread wait until another thread finishes. join(ms) waits at most that long.
  • Real life: sleep is setting a 5-minute alarm for a nap; join is 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.
ConstantValueMeaning
Thread.MIN_PRIORITY1Lowest priority hint
Thread.NORM_PRIORITY5Default
Thread.MAX_PRIORITY10Highest 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) before start(). 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.
  • synchronized lets only one thread at a time run the code for a given lock (monitor). Others wait in BLOCKED state.
  • A synchronized instance method locks this; a synchronized static method locks the Class object; a synchronized (obj) block locks obj.
  • 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

Pointsynchronized methodsynchronized block
Syntaxsynchronized void book() { }synchronized (lock) { ... }
Lock usedthis (or the Class for static methods)Any object you choose
ScopeWhole methodOnly the critical lines
PerformanceHolds the lock longerShorter lock time, better concurrency
ControlLessMore: can use a private lock object
Best forSmall methods that are fully criticalMethods 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 synchronized block on the same object, otherwise IllegalMonitorStateException is thrown.
  • Always call wait() inside a while loop 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()

Pointsleep()wait()
ClassThread (static method)Object (instance method)
Releases the lock?No, keeps all locksYes, releases the monitor of that object
Needs synchronized?NoYes, otherwise IllegalMonitorStateException
Wakes up whenTime is over or interruptednotify() / notifyAll(), time over (if given), or interrupted
State while pausedTIMED_WAITINGWAITING (or TIMED_WAITING with a timeout)
PurposePause for a whileWait for a condition signalled by another thread
Real lifeTaking a 10-minute napWaiting at the counter until your order number is called
L2

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 tryLock with 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.
  • volatile guarantees that every read sees the latest write, and prevents reordering around it.
  • volatile does NOT make compound actions like count++ 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.atomic classes (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 Callable returns a Future<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 ArrayList and HashMap are not thread-safe. Use the concurrent versions for shared data.
CollectionUse it forReal life
ConcurrentHashMapShared map with many readers and writers; atomic merge and computeLive vote counts per candidate
CopyOnWriteArrayListLists that are read often and changed rarelyList of event listeners
ArrayBlockingQueue / LinkedBlockingQueueProducer-consumer: put waits when full, take waits when emptyBakery shelf between baker and customers
ConcurrentLinkedQueueNon-blocking queue for high throughputLog messages from many threads
ConcurrentSkipListMapSorted concurrent mapLive 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.
  • CyclicBarrier makes 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

PointsynchronizedReentrantLock
SyntaxKeyword on a method or blocklock.lock() ... finally { lock.unlock(); }
ReleaseAutomatic at the end of the blockManual: always unlock in finally
Try without waitingNoYes: tryLock() or tryLock(time, unit)
Interruptible waitingNoYes: lockInterruptibly()
Fairness optionNoYes: new ReentrantLock(true)
Multiple conditionsOne wait set per objectMany Condition objects
Use whenSimple 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 sleep or 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.
PointPlatform threadVirtual thread
Managed byOperating systemJVM
CostAbout 1 MB stack, slow to createVery small, fast to create
How manyThousands at mostMillions
BlockingWastes an OS threadCheap: the carrier thread is freed
Createnew Thread(task)Thread.ofVirtual().start(task)
PoolingUse thread poolsDo 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

DoDo not
Prefer ExecutorService over creating raw threadsCreate a new thread for every small task
Share as little mutable data as possible; use immutable objectsLet many threads change plain fields without locks
Use concurrent collections and atomic classesShare HashMap or ArrayList across threads
Keep synchronized sections shortCall slow I/O while holding a lock
Take locks in a consistent orderNest locks in different orders in different methods
Handle InterruptedException (restore the flag)Swallow interrupts with an empty catch
Name your threads for readable logsLeave every thread as Thread-0, Thread-1
Shut down pools when doneUse deprecated stop(), suspend(), resume()
L3

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.

L4

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)
    }
}
L5

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().
L6

Practice Programs List

  1. Start two threads that print 1 to 5 with different names, and join both from main.
  2. Create a thread by extending Thread and another by implementing Runnable for the same task.
  3. Demonstrate that calling run() instead of start() keeps the code on the main thread.
  4. Print a thread state at each stage: NEW, TIMED_WAITING, WAITING, BLOCKED, TERMINATED.
  5. Simulate three file downloads in parallel and print the total time taken.
  6. Show a race condition with a shared counter, then fix it with synchronized and with AtomicInteger.
  7. Build a train reservation system where several threads book seats without overbooking.
  8. Implement chef and waiter communication using wait() and notifyAll().
  9. Rewrite the chef and waiter program using a BlockingQueue.
  10. Print odd and even numbers alternately using two threads.
  11. Write a deadlock with two locks, observe it hang, then fix it with a consistent lock order.
  12. Use an ExecutorService with 3 threads to serve 10 bank tokens.
  13. Ask three "shops" for a price using Callable and invokeAll, and print the lowest.
  14. Run 10,000 sleeping tasks on virtual threads (Java 21) and compare with a fixed pool of 100 threads.