Multithreading
Thread creation, synchronisation, wait-notify, Executor framework, and concurrent collections.
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?
Q2.What is deadlock? How can it be avoided?
Q3.Difference between `sleep()` and `wait()`?
🔘 MCQ Practice — Multithreading
MCQ 1.Which method starts a thread's execution in Java?
✓ Correct Answer: start()
MCQ 2.The `synchronized` keyword in Java is used to:
✓ 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.