Back to Java Programming
Java Programming

Multithreading

Thread creation, synchronisation, wait-notify, Executor framework, and concurrent collections.

BeginnerIntermediateAdvanced

What You Will Learn in Multithreading

Multithreading allows concurrent execution of two or more threads within a single Java program, enabling efficient CPU utilisation and responsive applications.

  • Thread lifecycle: NEW → RUNNABLE → RUNNING → BLOCKED/WAITING → TERMINATED.
  • Two ways to create a thread: extend Thread class, or implement Runnable interface (preferred).
  • `synchronized` keyword prevents race conditions by allowing only one thread to enter a critical section.
  • `wait()`, `notify()`, `notifyAll()` must be called within a synchronized block.
  • Executor Framework (ExecutorService, ThreadPool) is preferred over raw Thread creation.
  • Volatile keyword ensures visibility of variable changes across threads.

Syntax

// Method 1: Runnable (preferred)
class Task implements Runnable {
    public void run() { /* task code */ }
}
Thread t = new Thread(new Task());
t.start();

// Method 2: Extend Thread
class MyThread extends Thread {
    public void run() { /* task code */ }
}

Complete Code Example

class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }
    public int getCount() { return count; }
}
public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();
        Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) c.increment(); });
        Thread t2 = new Thread(() -> { for(int i=0;i<1000;i++) c.increment(); });
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println("Count: " + c.getCount()); // Count: 2000
    }
}

Example

A download manager runs file downloads in separate threads so the UI stays responsive.

Expected Exam Questions — Multithreading

Q1.What is a race condition and how do you prevent it?
Answer: A race condition occurs when multiple threads access shared data simultaneously and at least one modifies it, leading to inconsistent results. Prevent it using `synchronized` blocks/methods, `ReentrantLock`, or atomic variables like `AtomicInteger`.
Q2.What is deadlock? How can it be avoided?
Answer: Deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock. Avoid it by: using a consistent lock ordering, using `tryLock()` with timeout, minimising synchronized scope.
Q3.Difference between `sleep()` and `wait()`?
Answer: `sleep(ms)` pauses the thread for specified time without releasing the lock. `wait()` pauses the thread AND releases the lock, waiting until `notify()` or `notifyAll()` is called. `sleep()` is in Thread class; `wait()` is in Object class.

🔘 MCQ Practice — Multithreading

MCQ 1.Which method starts a thread's execution in Java?
A. run()
B. execute()
C. start()
D. launch()

✓ Correct Answer: start()

MCQ 2.The `synchronized` keyword in Java is used to:
A. Create a new thread
B. Prevent race conditions
C. Kill a thread
D. Sleep a thread

✓ Correct Answer: Prevent race conditions

Download Multithreading PDF Notes

Get the complete Multithreading notes as a PDF — free for enrolled students, or browse our public study materials library.

More Java Programming Topics

Related Subjects

Frequently Asked Questions — Multithreading

What is Multithreading in Java Programming?
Multithreading allows concurrent execution of two or more threads within a single Java program, enabling efficient CPU utilisation and responsive applications.
What is a race condition and how do you prevent it?
A race condition occurs when multiple threads access shared data simultaneously and at least one modifies it, leading to inconsistent results. Prevent it using `synchronized` blocks/methods, `ReentrantLock`, or atomic variables like `AtomicInteger`.
What is deadlock? How can it be avoided?
Deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock. Avoid it by: using a consistent lock ordering, using `tryLock()` with timeout, minimising synchronized scope.
Difference between `sleep()` and `wait()`?
`sleep(ms)` pauses the thread for specified time without releasing the lock. `wait()` pauses the thread AND releases the lock, waiting until `notify()` or `notifyAll()` is called. `sleep()` is in Thread class; `wait()` is in Object class.
How do I prepare Multithreading for exams?
To master Multithreading, start by reading the theory carefully, then go through solved examples step by step. Practice numericals (if applicable), revise key formulas, and attempt previous year questions. SII notes cover all these aspects in a structured manner.
Are these Multithreading notes free?
Yes! SII provides free access to Multithreading notes and introductory study materials. Enrolled students get full access to detailed notes, solved papers, and live doubt-clearing sessions.
Which exams ask questions from Multithreading?
Multithreading is an important topic tested in Beginner, Intermediate, Advanced board exams, as well as GATE (CS & IT), University Semester Exams. It frequently appears in both short-answer and long-answer sections.