Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 11

Java Multithreading

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Multithreading lets a Java program run several independent paths of execution (threads) inside one process.

This chapter explains threads, the thread lifecycle, ways to create threads, synchronization and inter-thread communication with wait, notify and notifyAll.

Modern CPUs have many cores and servers handle many requests at once.

Threads are core to Java interviews and to writing responsive applications.

Web servers handling parallel requests, background downloads, UI that stays responsive, parallel data processing, schedulers.

1

Multithreading in Java

Multithreading is the ability of a program to execute two or more threads concurrently within the same process. A thread is the smallest unit of execution; threads of one process share the heap and method area but each has its own stack and program counter.

In short: A thread is one worker inside your program. Multithreading means several workers sharing the same office but each doing a different task.

Think about it

Single-threaded programs waste multi-core hardware and freeze on slow I/O. Threads let work overlap. A restaurant: one chef (single thread) makes orders one by one, while several chefs (threads) prepare dishes at the same time in the same kitchen.

A process is an independent program with its own memory; threads inside a process share memory, so communication is cheap but risky.

Every Java program starts with the main thread; the JVM also runs background threads (GC, JIT compiler).

Concurrency means tasks make progress by interleaving (possibly on one core); parallelism means tasks literally run at the same time on several cores.

Benefits

better CPU use, responsiveness, simpler modelling of independent tasks.

Costs: complexity, race conditions, deadlocks and context-switch overhead.

Thread scheduling is done by the OS/JVM and is non-deterministic, so output order of unsynchronized threads can differ in every run.

Use join() to wait for a thread to finish.

Daemon threads (setDaemon(true)) do not stop the JVM from exiting.

For real applications prefer the java.

util.

concurrent executors instead of creating raw threads manually.

Key points

  • Process: Running program with its own address space.
  • Thread: Lightweight path of execution inside a process.
  • Concurrency: Dealing with many tasks by interleaving them.
  • Parallelism: Running tasks at the same instant on multiple cores.
  • Context switch: CPU switching from one thread to another.
  • Threads share heap; each thread has its own stack and PC register.
  • Thread scheduling order is not guaranteed.
  • main() runs in the "main" thread; the JVM waits for all non-daemon threads.
  • join() waits for a thread to die.

Example

Code
Splitting work between two threads:
public class MultiThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Cores: " + Runtime.getRuntime().availableProcessors());
        System.out.println("Running in: " + Thread.currentThread().getName());   // main

        long[] partial = new long[2];

        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 500; i++) partial[0] += i;
        });
        Thread t2 = new Thread(() -> {
            for (int i = 501; i <= 1000; i++) partial[1] += i;
        });

        t1.start();
        t2.start();
        t1.join();                      // wait for both workers
        t2.join();

        System.out.println(partial[0]); // 125250
        System.out.println(partial[1]); // 375250
        System.out.println(partial[0] + partial[1]);   // 500500
    }
}
2

Thread Lifecycle in Java

The lifecycle of a thread is the set of states a Thread object passes through, defined by Thread.State: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.

In short: A thread is born (NEW), starts (RUNNABLE), sometimes has to wait or sleep, and finally dies (TERMINATED).

Think about it

Knowing the states explains deadlocks, hung threads and the output of getState() questions. A bus passenger: waiting at stop (NEW), boarding and travelling (RUNNABLE), waiting for the door lock (BLOCKED), waiting for a friend (WAITING), napping for 10 minutes (TIMED_WAITING), reached destination (TERMINATED).

NEW: object created, start() not yet called.

RUNNABLE: after start(); the thread is either running or ready and waiting for CPU (Java does not separate "ready" and "running").

BLOCKED: waiting to enter a synchronized block because another thread holds the monitor.

WAITING: waiting indefinitely for another thread, entered by `Object.

wait(), Thread.

join() or LockSupport.

park()`; left through notify/notifyAll, thread end or unpark.

TIMED_WAITING: waiting for a limited time: sleep(ms), wait(ms), join(ms).

TERMINATED: run() finished normally or by an uncaught exception; a terminated thread cannot be restarted (IllegalThreadStateException).

getState() reports the current state, isAlive() is true between start and termination.

interrupt() sets the interrupt flag and wakes a sleeping/waiting thread with InterruptedException.

Calling start() twice on the same thread is illegal.

Key points

  • NEW: Created but not started.
  • RUNNABLE: Running or ready to run.
  • BLOCKED: Waiting for a monitor lock.
  • WAITING: Waiting without time limit for another thread.
  • TIMED_WAITING: Waiting up to a given time (sleep, timed wait/join).
  • TERMINATED: Finished execution.

Example

Code
Observing thread states:
public class LifecycleDemo {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println("Interrupted!");
            }
        });

        System.out.println(t.getState());   // NEW
        t.start();
        Thread.sleep(100);
        System.out.println(t.getState());   // TIMED_WAITING (inside sleep)
        t.join();
        System.out.println(t.getState());   // TERMINATED
        System.out.println(t.isAlive());    // false

        try {
            t.start();                      // cannot restart
        } catch (IllegalThreadStateException e) {
            System.out.println("Cannot start a thread twice");
        }

        // BLOCKED example
        Object lock = new Object();
        Thread holder = new Thread(() -> {
            synchronized (lock) {
                try { Thread.sleep(400); } catch (InterruptedException e) { }
            }
        });
        Thread waiter = new Thread(() -> {
            synchronized (lock) { System.out.println("waiter got the lock"); }
        });
        holder.start();
        Thread.sleep(100);                  // let holder take the lock first
        waiter.start();
        Thread.sleep(100);
        System.out.println(waiter.getState());   // BLOCKED
        holder.join();
        waiter.join();                           // waiter got the lock
    }
}

start()

NEW → RUNNABLE.

Creates a new call stack and calls run().

sleep / wait / join

sleep(ms) → TIMED_WAITING keeping locks; wait() → WAITING and releases the lock; join() waits for another thread.

synchronized contention

RUNNABLE → BLOCKED while another thread owns the lock.

run() ends

RUNNABLE → TERMINATED; cannot restart.

3

Creating Thread in Java

A thread can be created by extending the Thread class and overriding run(), by implementing Runnable (or using a lambda) and passing it to a Thread, or by submitting Runnable/Callable tasks to an ExecutorService. A thread begins only when start() is called.

In short: Write the job in run(), hand it to a Thread, and call start(). Never call run() yourself.

CPU runs processes in turns

Think about it

Choosing Runnable/Callable with executors is the standard, flexible and scalable way to run tasks. Writing a job card (Runnable) and giving it to a worker (Thread) who starts it on the shop floor.

Approach 1: `class MyThread extends Thread { public void run() {...

} }` — uses up your single inheritance.

Approach 2: `class Task implements Runnable and new Thread(task).

start()` — preferred because the class can still extend another class and the task can be reused by executors.

Approach 3: lambda `new Thread(() -> ...

)` since Runnable is a functional interface.

Approach 4: `ExecutorService pool = Executors.

newFixedThreadPool(n); Future<T> f = pool.

submit(callable);` — Callable returns a value and can throw checked exceptions; `future.

get()` blocks until the result is ready.

Always shutdown() the pool.

start() creates a new call stack and runs run() in the new thread; calling run() directly is a plain method call on the current thread.

Useful API: setName/getName, setPriority (1–10, only a hint), setDaemon, sleep, yield, join, interrupt, isInterrupted, Thread.

currentThread().

Starting a thread twice throws IllegalThreadStateException.

Key points

  • Runnable: Functional interface with void run().
  • Callable: Like Runnable but call() returns a value and may throw.
  • Future: Handle to a result that will be available later.
  • ExecutorService: Thread pool that runs submitted tasks.
  • Daemon thread: Background thread that does not keep the JVM alive.
  • start() = new thread; run() = normal call on the current thread.
  • Runnable preferred over extending Thread.
  • Callable returns a value; Runnable does not.
  • Always shut down executors.

Example

Code
Four ways to run code in a thread:
import java.util.concurrent.*;

public class CreateThreads {
    static class Worker extends Thread {                 // way 1
        public void run() {
            System.out.println("Worker thread: " + getName());
        }
    }

    static class Task implements Runnable {              // way 2
        public void run() {
            System.out.println("Runnable in: " + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws Exception {
        Worker w = new Worker();
        w.setName("W-1");
        w.start();
        w.join();                                        // Worker thread: W-1

        Thread t = new Thread(new Task(), "T-2");
        t.start();
        t.join();                                        // Runnable in: T-2

        Thread lam = new Thread(() ->                    // way 3: lambda
            System.out.println("Lambda in: " + Thread.currentThread().getName()), "L-3");
        lam.start();
        lam.join();                                      // Lambda in: L-3

        new Task().run();                                // Runnable in: main  (no new thread!)

        ExecutorService pool = Executors.newFixedThreadPool(2);   // way 4
        Callable<Integer> square = () -> 7 * 7;
        Future<Integer> result = pool.submit(square);
        System.out.println(result.get());                // 49
        pool.shutdown();
    }
}
4

Synchronization in Java

Synchronization is the technique of controlling access of multiple threads to shared resources so that only one thread at a time executes a critical section. In Java it is done with the synchronized keyword (methods and blocks), which uses the intrinsic lock (monitor) of an object.

In short: A synchronized block is a room with one key. Only the thread holding the key can enter; the others wait outside.

Threads share CPU · sync protects data

Think about it

Without it shared data gets corrupted in ways that are hard to reproduce. It is the heart of thread-safety questions. A bank counter with one teller window: customers (threads) queue so that two people do not update the same account at the same moment.

A race condition occurs when threads read-modify-write shared data without coordination: count++ is three steps (read, add, write) so two threads can overwrite each other, giving a total less than expected.

A `synchronized` instance method locks this; a `static synchronized` method locks the Class object; a block `synchronized (obj) { ...

}` locks the given object and is preferred because it keeps the critical section small.

Locks are reentrant (a thread already holding a lock can enter again).

Synchronization gives mutual exclusion AND visibility (changes made inside are visible to the next thread acquiring the same lock).

volatile gives visibility and ordering for a single variable but NOT atomicity for compound actions.

For simple counters use AtomicInteger; for flexible locking use ReentrantLock.

Deadlock happens when two threads each hold a lock the other needs; avoid it by acquiring locks in a fixed global order.

Over-synchronizing hurts performance.

Key points

  • Critical section: Code that accesses shared state and must not run concurrently.
  • Race condition: Result depends on timing of threads.
  • Monitor / intrinsic lock: Lock built into every Java object.
  • volatile: Guarantees visibility of a variable, not atomic compound operations.
  • Deadlock: Threads wait forever for each other locks.
  • synchronized method locks this; static synchronized locks ClassName.class.
  • Prefer small synchronized blocks over whole methods.
  • count++ is NOT atomic; use synchronized, AtomicInteger or a Lock.
  • volatile: visibility only. Locks: visibility + mutual exclusion.

Example

Code
Race condition and three ways to fix it:
import java.util.concurrent.atomic.AtomicInteger;

public class SyncDemo {
    static class UnsafeCounter {
        int count;
        void inc() { count++; }                       // race condition
    }
    static class SafeCounter {
        private int count;
        synchronized void inc() { count++; }          // locks 'this'
        synchronized int get() { return count; }
    }
    static class BlockCounter {
        private int count;
        private final Object lock = new Object();
        void inc() { synchronized (lock) { count++; } }
        int get() { synchronized (lock) { return count; } }
    }

    static void runTwice(Runnable r) throws InterruptedException {
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); b.start();
        a.join(); b.join();
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeCounter u = new UnsafeCounter();
        runTwice(() -> { for (int i = 0; i < 100000; i++) u.inc(); });
        System.out.println("Unsafe : " + u.count);    // usually less than 200000

        SafeCounter s = new SafeCounter();
        runTwice(() -> { for (int i = 0; i < 100000; i++) s.inc(); });
        System.out.println("Safe   : " + s.get());    // 200000

        BlockCounter b = new BlockCounter();
        runTwice(() -> { for (int i = 0; i < 100000; i++) b.inc(); });
        System.out.println("Block  : " + b.get());    // 200000

        AtomicInteger atomic = new AtomicInteger();
        runTwice(() -> { for (int i = 0; i < 100000; i++) atomic.incrementAndGet(); });
        System.out.println("Atomic : " + atomic.get());// 200000
    }
}
5

wait notify and notifyAll

wait(), notify() and notifyAll() are methods of java.lang.Object used for inter-thread communication. A thread calls wait() to release the lock and sleep until another thread calls notify() (wakes one waiting thread) or notifyAll() (wakes all waiting threads) on the same object. They must be called from a synchronized context.

In short: wait() means: I will sleep and give up the key until something changes. notify() means: wake one sleeper, the condition may have changed.

Think about it

Threads often need to wait for a condition (buffer not empty/not full). Busy-waiting wastes CPU; wait/notify lets them sleep efficiently. A kitchen pass: the cook waits for the counter to be free; the waiter rings a bell (notify) when it is empty.

Calling them without owning the monitor throws IllegalMonitorStateException.

wait() releases the monitor and moves the thread to the WAITING state (or TIMED_WAITING for wait(ms)); when woken it must reacquire the lock before continuing.

ALWAYS call wait() inside a `while (!

condition) loop, not an if`, because of spurious wake-ups and because another thread may have changed the condition again.

notify() picks an arbitrary single waiter, so use notifyAll() when waiters wait for different conditions (for example both producers and consumers) to avoid lost signals.

Difference from sleep(): sleep is a Thread static method, keeps the lock and wakes by time; wait is an Object method, releases the lock and wakes by notify (or timeout).

This is the basis of the producer-consumer problem and of BlockingQueue in java.

util.

concurrent, which is the easier modern alternative.

Key points

  • wait(): Release the lock and wait to be notified.
  • notify(): Wake one waiting thread.
  • notifyAll(): Wake all waiting threads; they compete for the lock.
  • Spurious wake-up: Waking without notify; hence the while loop.
  • Producer-consumer: One side produces items, the other consumes them via a shared buffer.
  • Methods of Object, not Thread; need synchronized on the same object.
  • wait releases the lock; sleep does not.
  • Use while(condition) wait();
  • Prefer notifyAll() unless only one kind of waiter exists.

Read more

Example

Code
Producer-consumer with wait and notifyAll:
public class ProducerConsumer {
    static class Buffer {                                  // holds one item
        private int value;
        private boolean full = false;

        synchronized void put(int v) throws InterruptedException {
            while (full) wait();                           // wait until empty
            value = v;
            full = true;
            System.out.println("Produced " + v);
            notifyAll();                                   // wake consumer
        }

        synchronized int take() throws InterruptedException {
            while (!full) wait();                          // wait until full
            full = false;
            System.out.println("Consumed " + value);
            notifyAll();                                   // wake producer
            return value;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Buffer buf = new Buffer();

        Thread producer = new Thread(() -> {
            try { for (int i = 1; i <= 3; i++) buf.put(i); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        Thread consumer = new Thread(() -> {
            try { for (int i = 1; i <= 3; i++) buf.take(); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });

        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
        // Produced 1, Consumed 1, Produced 2, Consumed 2, Produced 3, Consumed 3
    }
}

Solved examples

Example 01 · Basic

What is the difference between t.start() and t.run()?

Given Data:
    Required To Find:

    Explanation

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: start() asks the JVM to create a new call stack and then invokes run() there
    Step 2: run() called directly is an ordinary method call on the current thread
    Step 3: So only start() gives concurrency
    Final Answer: start() creates a new thread; run() runs in the caller thread.

    Approach note: Calling start() twice throws IllegalThreadStateException.

    Example 02 · Basic

    Name the thread state after start() when the thread calls Thread.sleep(1000).

    Given Data:
      Required To Find:

      Thread state

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: After start() the state is RUNNABLE
      Step 2: sleep with a time limit puts it into the timed state
      Final Answer: TIMED_WAITING

      Approach note: wait() with no argument gives WAITING; synchronized contention gives BLOCKED.

      Example 03 · Intermediate

      Two threads each execute count++ 1000 times on a shared int. Why can the final value be less than 2000, and how do you fix it?

      Given Data:
        Required To Find:

        Cause and fix

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: count++ is read, add, write — three separate steps
        Step 2: Two threads can read the same value and both write back value + 1
        Step 3: Fix with synchronized methods/blocks or AtomicInteger
        Final Answer: Lost updates from a race condition; use synchronized or AtomicInteger to always get 2000.

        Approach note: volatile alone does not fix it, because the increment is still not atomic.

        Example 04 · Intermediate

        Why must wait() be inside a while loop?

        Given Data:
          Required To Find:

          Reason

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: A thread can wake up without notify (spurious wake-up)
          Step 2: Another thread may have consumed the item before this thread reacquired the lock
          Step 3: The condition must be re-checked every time
          Final Answer: Use while (!condition) wait(); so the condition is verified after each wake-up.

          Approach note: Write it as a standard pattern and never use if.

          Real-world applications

          Java

          Using Java Multithreading in real projects

          Web servers handling parallel requests, background downloads, UI that stays responsive, parallel data processing, schedulers.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Calling run() starts a new thread.

          Why this is wrong: run() is just a method; only start() creates a thread.

          ✅ Verified Truth: Always call start().

          ⚠️ Exam Tip: Output-order questions test this.

          ❌ Myth: sleep() releases the lock.

          Why this is wrong: sleep keeps all monitors it holds.

          ✅ Verified Truth: wait() releases the lock; sleep() does not.

          ⚠️ Exam Tip: Say: sleep = Thread, wait = Object.

          ❌ Myth: volatile makes count++ thread-safe.

          Why this is wrong: count++ is a compound read-modify-write.

          ✅ Verified Truth: Use synchronized or AtomicInteger.

          ⚠️ Exam Tip: volatile = visibility only.

          ❌ Myth: Thread priority guarantees execution order.

          Why this is wrong: Priority is only a hint to the scheduler.

          ✅ Verified Truth: Use synchronization or join for ordering.

          ⚠️ Exam Tip: Output of unsynchronized threads is non-deterministic.

          Revision notes

          Multithreading lets a Java program run several independent paths of execution (threads) inside one process. This chapter explains threads, the thread lifecycle, ways to create threads, synchronization and inter-thread communication with wait, notify and notifyAll.

          High-Yield Quick Revision Points

          1. Threads share heap; each has its own stack
          2. States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
          3. start() creates a thread; run() is a normal call; no restart
          4. Runnable preferred; Callable + Future for results; shutdown executors
          5. synchronized = mutual exclusion + visibility; count++ is not atomic
          6. wait/notify/notifyAll: in synchronized, with while loop; wait releases lock

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which method starts a new thread?

          Question 2 · MCQ (Interview / semester)

          Which is NOT a state in Thread.State?

          Question 3 · MCQ (Interview / semester)

          wait() must be called from:

          Question 4 · MCQ (Interview / semester)

          Which interface can return a value from a task?

          Question 5 · MCQ (Interview / semester)

          Which statement about sleep() is true?

          Question 6 · MCQ (Interview / semester)

          What does static synchronized lock?