Multithreading Part 2 — Synchronization
Race conditions, synchronized keyword, wait/notify, thread lifecycle states
- Identify and fix race conditions using synchronized
- Use wait(), notify(), and notifyAll() for thread coordination
- Map and trace all six thread lifecycle states
Series Context:
This is Part 2 of the Java Multithreading series. It covers thread creation mechanisms, the full thread lifecycle, monitor locks, synchronization, and inter-thread communication via wait(), notify(), and notifyAll().
Table of Contents
- Two Ways to Create a Thread
- Runnable Interface — Architecture & Internal Working
- Method 1: Implementing the Runnable Interface
- Method 2: Extending the Thread Class
- Comparison: Runnable vs Extending Thread
- Thread Lifecycle
- Thread States — Detailed Breakdown
- Monitor Lock (Object Lock)
- Synchronized Block vs Synchronized Method
- Monitor Lock Example — Practical Demo
- Inter-Thread Communication — wait(), notify(), notifyAll()
- Producer-Consumer Problem — Implementation
- Spurious Wakeup — Why while Instead of if
- Deprecated Thread Methods — stop(), suspend(), resume()
- Assignment — Full Producer-Consumer with Queue
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary
1. Two Ways to Create a Thread
Java provides two mechanisms to create a thread:
| Approach | How |
|---|---|
Implement Runnable interface | Create a class that implements Runnable, pass it to a Thread constructor |
Extend Thread class | Create a class that extends Thread, override run(), call start() directly |
Why Does Java Provide Two Ways?
This is a very important interview question.
In Java, a class can extend only one parent class, but it can implement multiple interfaces.
Consider this scenario:
1class MyClass extends SomeOtherClass {2 // MyClass already has a parent — cannot also extend Thread!3}If your class already extends another class, you cannot also extend Thread, because Java does not support multiple inheritance through classes.
However, you can implement Runnable in addition to extending another class:
1class MyClass extends SomeOtherClass implements Runnable {2 @Override3 public void run() {4 // thread work here5 }6}This is why Java provides both options — to handle all design scenarios without forcing the programmer to give up class inheritance.
2. Runnable Interface Architecture & Internal Working
Understanding the internal class architecture is essential before writing code.
2.1 The `Runnable` Interface
1@FunctionalInterface2public interface Runnable {3 void run();4}Runnableis a functional interface — it has exactly one abstract method:run().- It is not a thread. It is a plain interface that defines a task to be executed.
- Because it is a functional interface, you can use a lambda expression to implement it.
2.2 The `Thread` Class
1public class Thread implements Runnable {2 private Runnable target;3
4 public Thread(Runnable target) {5 this.target = target;6 }7
8 @Override9 public void run() {10 if (target != null) {11 target.run(); // delegates to your Runnable12 }13 }14
15 public synchronized void start() {16 // native method — creates OS-level thread and eventually calls run()17 }18 // ... sleep, interrupt, join, getName, etc.19}Key observations:
Threaditself implementsRunnable.Threadholds a fieldtarget— a reference to theRunnableobject you pass to the constructor.- When
start()is called → the JVM creates a new OS thread → that thread callsrun()→run()delegates totarget.run()if a target was set.
3. Method 1: Implementing the Runnable Interface
3.1 Step-by-Step Process
Step 1 — Create a class that implements Runnable and override run():
1class MultithreadingLearning implements Runnable {2 @Override3 public void run() {4 System.out.println("Code executed by thread: "5 + Thread.currentThread().getName());6 }7}Thread class is what actually creates and manages the OS thread.Step 2 — Create an instance of your Runnable class:
1MultithreadingLearning runnableObj = new MultithreadingLearning();Step 3 — Pass the Runnable object to the Thread constructor:
1Thread thread = new Thread(runnableObj);At this point the thread exists as a Java object but has not started. The state is NEW.
Step 4 — Start the thread:
1thread.start();This transitions the thread from NEW → RUNNABLE. Internally, start() calls run(), which checks if (target != null) and calls target.run() — invoking your MultithreadingLearning.run().
3.2 Complete Example
1public class RunnableDemo {2
3 // Step 1: Runnable implementation4 static class MultithreadingLearning implements Runnable {5 @Override6 public void run() {7 System.out.println("Code executed by thread: "8 + Thread.currentThread().getName());9 }10 }11
12 public static void main(String[] args) {13 System.out.println("Main thread: " + Thread.currentThread().getName());14
15 // Step 2: Create Runnable object16 MultithreadingLearning runnableObj = new MultithreadingLearning();17
18 // Step 3: Pass to Thread constructor19 Thread thread = new Thread(runnableObj);20
21 // Step 4: Start the thread22 thread.start();23
24 System.out.println("Main thread finished.");25 }26}Main thread: main Main thread finished. Code executed by thread: Thread-0
join().3.3 Lambda Expression Shortcut
Since Runnable is a functional interface, you can skip creating a separate class and use a lambda:
1Thread thread = new Thread(() -> {2 System.out.println("Code executed by thread: "3 + Thread.currentThread().getName());4});5thread.start();This is functionally identical to the class-based approach. The lambda () -> { ... } is the implementation of Runnable.run().
3.4 Internal Execution Flow
3.5 Why Runnable is Preferred in Industry
Because a class implementing Runnable can:
- Extend another class (not limited to one parent)
- Implement multiple other interfaces
- Do many other things besides threading
- Be passed to
ExecutorService, thread pools, etc.
1// This is perfectly valid with Runnable approach:2class MyService extends BaseService implements Runnable, Serializable {3 @Override4 public void run() { /* thread task */ }5}This would be impossible if MyService had to extend Thread.
4. Method 2: Extending the Thread Class
4.1 Step-by-Step Process
Step 1 — Create a class that extends Thread and override run():
1class MultithreadingLearning extends Thread {2 @Override3 public void run() {4 System.out.println("Code executed by thread: "5 + Thread.currentThread().getName());6 }7}This class IS a thread — it inherits all thread lifecycle methods (start(), sleep(), interrupt(), etc.) directly from Thread.
Step 2 — Create an instance of your subclass:
1MultithreadingLearning myThread = new MultithreadingLearning();No separate Thread object is needed — your object is the thread.
Step 3 — Start the thread:
1myThread.start();start() is inherited from Thread. It calls run() on myThread — which is your overridden run() method (polymorphism).
4.2 Why You Must Override `run()`
If you don't override run(), the parent Thread.run() is called:
1@Override2public void run() {3 if (target != null) {4 target.run();5 }6 // otherwise: does nothing and returns7}Since no target was set (you didn't pass a Runnable to the constructor), it does nothing. So always override run() when extending Thread.
4.3 Complete Example
1public class ExtendThreadDemo {2
3 static class MultithreadingLearning extends Thread {4 @Override5 public void run() {6 System.out.println("Code executed by thread: "7 + Thread.currentThread().getName());8 }9 }10
11 public static void main(String[] args) {12 System.out.println("Main thread: " + Thread.currentThread().getName());13
14 MultithreadingLearning myThread = new MultithreadingLearning();15 myThread.start(); // internally calls overridden run()16
17 System.out.println("Main thread finished.");18 }19}Main thread: main Main thread finished. Code executed by thread: Thread-0
5. Comparison: Runnable vs Extending Thread
| Feature | implements Runnable | extends Thread |
|---|---|---|
| Multiple inheritance | ✅ Can still extend another class | ❌ Cannot extend any other class |
| Object is a Thread? | ❌ No — just a task | ✅ Yes — directly a thread |
| Need separate Thread object? | ✅ Yes — new Thread(runnableObj) | ❌ No — object itself is the thread |
| Works with thread pools? | ✅ Yes (ExecutorService, etc.) | ❌ Not natively |
| Preferred in industry? | ✅ Yes | ❌ Generally avoided |
| Flexibility | ✅ High | ❌ Limited |
| Override required | run() | run() |
implements Runnable (or Callable) is almost always preferred. Extending Thread is taught for conceptual understanding but rarely used in real applications.6. Thread Lifecycle
Every thread in Java passes through well-defined states during its lifetime.
Thread.State enum has: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. When a thread is actually executing on the CPU, it is still in the RUNNABLE state — the JVM doesn't distinguish between "waiting for CPU" and "currently on CPU" at the Java level.7. Thread States Detailed Breakdown
7.1 NEW
1Thread t = new Thread(() -> System.out.println("hello"));2// t is in NEW state — object exists, OS thread not created yet- Thread object is created in memory.
- No OS-level thread has been created yet.
start()has not been called.
7.2 RUNNABLE
1t.start(); // transitions to RUNNABLE- Thread is ready to execute and waiting for CPU time.
- Once the OS scheduler assigns it CPU time, it begins executing
run(). - Switching between "waiting for CPU" and "executing" is called context switching — the thread moves back and forth rapidly, giving the illusion of parallel execution on a single core.
7.3 BLOCKED
A thread enters the BLOCKED state when it tries to acquire a monitor lock (enter a synchronized block/method) that is currently held by another thread.
1Thread 1 → holds lock on object A → inside synchronized block2Thread 2 → tries to enter synchronized block on same object A → BLOCKEDKey rule: When a thread enters the BLOCKED state, it releases all monitor locks it currently holds.
Once the lock is released by Thread 1, Thread 2 can acquire it and transitions back to RUNNABLE.
7.4 WAITING
A thread enters the WAITING state when wait() is called explicitly. It stays WAITING indefinitely until another thread calls notify() or notifyAll() on the same object.
1synchronized(obj) {2 obj.wait(); // thread goes to WAITING — releases monitor lock3}Key rules:
wait()can only be called from inside asynchronizedblock/method.- When entering WAITING, the thread releases the monitor lock.
- It will not automatically wake up — it waits until
notify()/notifyAll()is called.
7.5 TIMED_WAITING
Similar to WAITING, but with a timeout. The thread automatically returns to RUNNABLE after the time expires, even if no notify() is called.
Common causes:
Thread.sleep(milliseconds)obj.wait(milliseconds)thread.join(milliseconds)
1Thread.sleep(5000); // TIMED_WAITING for 5 secondsKey rule: During TIMED_WAITING (e.g., sleep()), the thread does NOT release monitor locks it holds. This is a critical difference from WAITING (caused by wait()).
| State | Releases monitor lock? | Wakes up automatically? |
|---|---|---|
BLOCKED | ✅ Yes | ✅ When lock is available |
WAITING | ✅ Yes | ❌ Only via notify() |
TIMED_WAITING | ❌ No | ✅ After timeout |
7.6 TERMINATED
Thread has finished executing run() — either normally or due to an uncaught exception.
1// After run() completes:2System.out.println(t.getState()); // TERMINATEDstart() on a terminated thread throws IllegalThreadStateException.8. Monitor Lock (Object Lock)
8.1 What Is a Monitor Lock?
Every Java object has an intrinsic lock, also called a monitor lock or object lock. It is built into the JVM — you don't create it; it exists automatically for every object.
Purpose: Ensure that only one thread at a time can execute a critical section (a synchronized block or method) on a particular object.
8.2 How Monitor Locks Work
1Object obj = new Object();2
3Thread 1 → enters synchronized(obj) → acquires monitor lock on obj4Thread 2 → tries to enter synchronized(obj) → must wait (BLOCKED)5
6Thread 1 exits synchronized block → releases monitor lock7Thread 2 → acquires monitor lock → proceeds8.3 Monitor Lock is Per-Object
Each object has its own monitor lock. Two threads using different objects do not block each other:
1class Counter {2 synchronized void increment() { ... }3}4
5Counter c1 = new Counter();6Counter c2 = new Counter();7
8Thread t1 = new Thread(() -> c1.increment()); // locks c1's monitor9Thread t2 = new Thread(() -> c2.increment()); // locks c2's monitor — no conflict10t1.start();11t2.start(); // both run concurrently — they use different objectsBut if both threads share the same object:
1Counter shared = new Counter();2
3Thread t1 = new Thread(() -> shared.increment()); // locks shared's monitor4Thread t2 = new Thread(() -> shared.increment()); // must wait for t1 to release8.4 Monitor Lock and Thread States
| Thread action | Monitor lock effect |
|---|---|
Enters synchronized block | Acquires monitor lock |
Exits synchronized block | Releases monitor lock |
Calls wait() | Releases monitor lock, enters WAITING |
Returns from wait() (notified) | Re-acquires monitor lock |
Enters sleep() | Does NOT release monitor lock |
| Enters BLOCKED state | Releases monitor lock |
9. Synchronized Block vs Synchronized Method
9.1 Synchronized Method
1class Counter {2 synchronized void increment() {3 // entire method is a critical section4 // monitor lock is on 'this' (the Counter object)5 }6}The lock is placed on this — the instance of the class. Only one thread can execute any synchronized method on the same instance at a time.
9.2 Synchronized Block
1class Counter {2 void doWork() {3 System.out.println("Before sync — any thread can be here");4
5 synchronized (this) {6 // only this block is critical7 // monitor lock on 'this'8 }9
10 System.out.println("After sync — any thread can be here");11 }12}Advantage of synchronized block: More granular control. Code outside the block runs concurrently; only the critical section is protected. This improves throughput.
You can also lock on a specific object instead of this:
1private final Object lock = new Object();2
3void doWork() {4 synchronized (lock) {5 // critical section locked on 'lock' object6 }7}9.3 Static Synchronized Methods
When synchronized is placed on a static method, the monitor lock is on the Class object (not an instance):
1class Counter {2 static synchronized void staticIncrement() {3 // lock is on Counter.class4 }5}All instances of Counter share this one class-level lock.
10. Monitor Lock Example Practical Demo
10.1 Scenario
Three threads operate on the same object:
- Thread 1 → calls
taskOne()— synchronized, sleeps for 10 seconds - Thread 2 → calls
taskTwo()— has code before the synchronized block, then enters a synchronized block - Thread 3 → calls
taskThree()— no synchronization
1public class MonitorLockExample {2
3 // Synchronized method — locks the entire method on 'this'4 synchronized void taskOne() {5 System.out.println("Inside Task One — Thread: "6 + Thread.currentThread().getName());7 try {8 Thread.sleep(10000); // sleeps 10s — holds the lock while sleeping9 } catch (InterruptedException e) {10 e.printStackTrace();11 }12 System.out.println("Task One completed");13 }14
15 void taskTwo() {16 // This runs before the lock is needed — any thread can be here17 System.out.println("Task Two: BEFORE synchronized block — Thread: "18 + Thread.currentThread().getName());19
20 synchronized (this) {21 // must wait for taskOne's lock to be released22 System.out.println("Task Two: INSIDE synchronized block");23 }24 }25
26 void taskThree() {27 // No synchronization — runs freely28 System.out.println("Task Three completed — Thread: "29 + Thread.currentThread().getName());30 }31
32 public static void main(String[] args) {33 MonitorLockExample obj = new MonitorLockExample(); // ONE shared object34
35 Thread t1 = new Thread(() -> obj.taskOne());36 Thread t2 = new Thread(() -> obj.taskTwo());37 Thread t3 = new Thread(() -> obj.taskThree());38
39 t1.start();40 t2.start();41 t3.start();42 }43}10.2 Step-by-Step Execution
Expected Output:
1Inside Task One — Thread: Thread-02Task Two: BEFORE synchronized block — Thread: Thread-13Task Three completed — Thread: Thread-24[... 10 seconds pass ...]5Task One completed6Task Two: INSIDE synchronized blocktaskThree() has no synchronization. Thread 2's "BEFORE synchronized" line also prints immediately — only the part inside the synchronized block waits.11. Inter-Thread Communication wait(), notify(), notifyAll()
11.1 Why Do We Need Inter-Thread Communication?
When two threads share a resource and one thread's work depends on the state set by another thread, they need a way to coordinate. Without communication, you'd have to use "busy waiting" (a thread constantly checking a condition in a loop), which wastes CPU.
Java's solution: wait(), notify(), notifyAll() — defined in Object (not Thread), so every object supports them.
11.2 Rules for wait(), notify(), notifyAll()
wait(), notify(), notifyAll() — MUST be called from inside a synchronized block or synchronized method. Calling them outside throws IllegalMonitorStateException.| Method | Behaviour |
|---|---|
wait() | Releases the monitor lock and puts the thread into WAITING state until notified |
wait(long ms) | Same as wait() but auto-wakes after ms milliseconds (TIMED_WAITING) |
notify() | Wakes up one arbitrary waiting thread on this object's monitor |
notifyAll() | Wakes up all threads waiting on this object's monitor |
11.3 Method Signatures
1// All defined in java.lang.Object2public final void wait() throws InterruptedException3public final void wait(long timeoutMillis) throws InterruptedException4public final native void notify()5public final native void notifyAll()11.4 Shared Resource Single Item Example
Scenario: One producer thread produces a single item. One consumer thread consumes it. The consumer must wait if no item is available.
1class SharedResource {2 private boolean itemPresent = false;3
4 synchronized void addItem() {5 itemPresent = true;6 System.out.println("Producer thread: item added. Calling notifyAll()...");7 notifyAll(); // wake up threads waiting on this object8 }9
10 synchronized void consumeItem() throws InterruptedException {11 System.out.println("Consumer thread: inside consumeItem()");12
13 while (!itemPresent) {14 System.out.println("Consumer thread: item not available — waiting...");15 wait(); // releases monitor lock and waits16 // after notify, re-checks the while condition17 }18
19 System.out.println("Consumer thread: item consumed!");20 itemPresent = false;21 }22}23
24public class InterThreadComm {25 public static void main(String[] args) {26 SharedResource resource = new SharedResource();27
28 Thread producerThread = new Thread(() -> {29 try {30 System.out.println("Producer thread started. Sleeping 3 seconds...");31 Thread.sleep(3000); // ensure consumer runs and waits first32 resource.addItem();33 } catch (InterruptedException e) {34 e.printStackTrace();35 }36 });37
38 Thread consumerThread = new Thread(() -> {39 try {40 resource.consumeItem();41 } catch (InterruptedException e) {42 e.printStackTrace();43 }44 });45
46 producerThread.start();47 consumerThread.start();48 }49}Producer thread started. Sleeping 3 seconds... Consumer thread: inside consumeItem() Consumer thread: item not available — waiting... [... 3 seconds ...] Producer thread: item added. Calling notifyAll()... Consumer thread: item consumed!
11.5 Step-by-Step Execution Flow
12. Producer-Consumer Problem Implementation
12.1 Class: SharedResource
1class SharedResource {2 private boolean itemPresent = false;3
4 // Called by the producer thread5 synchronized void addItem() {6 itemPresent = true;7 System.out.println("[" + Thread.currentThread().getName()8 + "] Item added. Notifying waiting threads...");9 notifyAll();10 }11
12 // Called by the consumer thread13 synchronized void consumeItem() throws InterruptedException {14 System.out.println("[" + Thread.currentThread().getName()15 + "] consumeItem() called.");16
17 // While loop — guards against spurious wakeups18 while (!itemPresent) {19 System.out.println("[" + Thread.currentThread().getName()20 + "] Item not available. Waiting...");21 wait(); // releases lock, enters WAITING22 }23
24 System.out.println("[" + Thread.currentThread().getName()25 + "] Item consumed.");26 itemPresent = false;27 }28}12.2 Class: ProduceTask (Runnable)
1class ProduceTask implements Runnable {2 private final SharedResource sharedResource;3
4 ProduceTask(SharedResource sharedResource) {5 this.sharedResource = sharedResource;6 }7
8 @Override9 public void run() {10 System.out.println("[" + Thread.currentThread().getName()11 + "] Producer thread started. Sleeping 5 seconds...");12 try {13 Thread.sleep(5000); // simulate production delay14 sharedResource.addItem();15 } catch (InterruptedException e) {16 Thread.currentThread().interrupt();17 }18 }19}12.3 Class: ConsumeTask (Runnable)
1class ConsumeTask implements Runnable {2 private final SharedResource sharedResource;3
4 ConsumeTask(SharedResource sharedResource) {5 this.sharedResource = sharedResource;6 }7
8 @Override9 public void run() {10 System.out.println("[" + Thread.currentThread().getName()11 + "] Consumer thread started.");12 try {13 sharedResource.consumeItem();14 } catch (InterruptedException e) {15 Thread.currentThread().interrupt();16 }17 }18}12.4 Main Class
1public class ProducerConsumerDemo {2 public static void main(String[] args) {3 System.out.println("Main method started.");4
5 SharedResource sharedResource = new SharedResource();6
7 // Both threads share the SAME SharedResource object8 Thread producerThread = new Thread(new ProduceTask(sharedResource), "ProducerThread");9 Thread consumerThread = new Thread(new ConsumeTask(sharedResource), "ConsumerThread");10
11 producerThread.start();12 consumerThread.start();13 }14}Main method started. [ProducerThread] Producer thread started. Sleeping 5 seconds... [ConsumerThread] Consumer thread started. [ConsumerThread] consumeItem() called. [ConsumerThread] Item not available. Waiting... [ProducerThread] Item added. Notifying waiting threads... [ConsumerThread] Item consumed.
12.5 Lambda Version (Equivalent, No Separate Classes)
1public class ProducerConsumerLambda {2 public static void main(String[] args) {3 SharedResource resource = new SharedResource();4
5 Thread producerThread = new Thread(() -> {6 try {7 System.out.println("Producer: sleeping 3 seconds...");8 Thread.sleep(3000);9 resource.addItem();10 } catch (InterruptedException e) {11 Thread.currentThread().interrupt();12 }13 }, "ProducerThread");14
15 Thread consumerThread = new Thread(() -> {16 try {17 resource.consumeItem();18 } catch (InterruptedException e) {19 Thread.currentThread().interrupt();20 }21 }, "ConsumerThread");22
23 producerThread.start();24 consumerThread.start();25 }26}13. Spurious Wakeup Why `while` Instead of `if`
13.1 What Is Spurious Wakeup?
A spurious wakeup is when a thread waiting in wait() wakes up without being notified — caused by low-level OS or JVM signal noise. This is rare but possible, and the Java specification explicitly permits it.
13.2 The Problem with `if`
1// DANGEROUS — if condition2synchronized void consumeItem() throws InterruptedException {3 if (!itemPresent) {4 wait(); // wakes up spuriously — itemPresent is STILL false!5 }6 // proceeds to consume even though item isn't ready — BUG!7 System.out.println("consuming..."); // could crash or produce wrong result8}If the thread wakes up spuriously (without notify()), itemPresent is still false, but the if block won't check again — it just falls through and consumes a non-existent item.
13.3 The Fix `while` Loop
1// CORRECT — while loop2synchronized void consumeItem() throws InterruptedException {3 while (!itemPresent) { // re-checks condition every time it wakes up4 wait();5 }6 // Only reaches here if itemPresent is ACTUALLY true7 System.out.println("consuming...");8}If the thread wakes spuriously, while re-evaluates the condition. If itemPresent is still false, it calls wait() again. This is the standard pattern recommended by Oracle's Java documentation.
while loop, never an if statement, when checking the condition around wait().14. Deprecated Thread Methods stop(), suspend(), resume()
14.1 `Thread.stop()` Deprecated
1thread.stop(); // ❌ DEPRECATED — do not useWhy deprecated: stop() immediately kills the thread and forcibly releases all monitor locks it holds. This can leave shared data in an inconsistent/corrupted state — other threads might see a half-written object.
How to properly stop a thread — use a volatile flag:
1class StoppableTask implements Runnable {2 private volatile boolean running = true;3
4 public void stop() {5 running = false;6 }7
8 @Override9 public void run() {10 while (running) {11 // do work12 }13 System.out.println("Thread stopped gracefully.");14 }15}16
17// Usage:18StoppableTask task = new StoppableTask();19Thread t = new Thread(task);20t.start();21
22Thread.sleep(2000);23task.stop(); // signals the thread to stop gracefullyThe volatile keyword ensures the running flag update is visible to the thread immediately (no CPU cache caching issues).
14.2 `Thread.suspend()` and `Thread.resume()` Deprecated
1thread.suspend(); // ❌ DEPRECATED2thread.resume(); // ❌ DEPRECATEDWhy deprecated: suspend() pauses the thread while still holding its monitor locks. If another thread tries to acquire those same locks, it deadlocks forever (the suspended thread never releases its locks, so nothing can resume it).
Correct alternative: Use wait() / notify() for controlled pause/resume behavior.
15. Assignment Full Producer-Consumer with Queue
This is a classic Computer Science concurrency problem. Implement the following:
Problem Statement:
Two threads — a Producer and a Consumer — share a common fixed-size buffer (a Queue):
- The Producer generates data and adds it to the queue.
- The Consumer reads and removes data from the queue.
- If the queue is FULL, the producer must wait — it should not add more items.
- If the queue is EMPTY, the consumer must wait — there is nothing to consume.
Skeleton to complete:
1import java.util.LinkedList;2import java.util.Queue;3
4class SharedBuffer {5 private final Queue<Integer> queue = new LinkedList<>();6 private final int MAX_SIZE = 5;7
8 synchronized void produce(int item) throws InterruptedException {9 while (queue.size() == MAX_SIZE) {10 // TODO: buffer full — producer must wait11 }12 // TODO: add item to queue13 // TODO: notify consumer14 }15
16 synchronized void consume() throws InterruptedException {17 while (queue.isEmpty()) {18 // TODO: buffer empty — consumer must wait19 }20 // TODO: remove and print item from queue21 // TODO: notify producer22 }23}24
25public class ProducerConsumerQueue {26 public static void main(String[] args) {27 SharedBuffer buffer = new SharedBuffer();28
29 Thread producer = new Thread(() -> {30 for (int i = 1; i <= 10; i++) {31 try {32 buffer.produce(i);33 } catch (InterruptedException e) {34 Thread.currentThread().interrupt();35 }36 }37 }, "Producer");38
39 Thread consumer = new Thread(() -> {40 for (int i = 1; i <= 10; i++) {41 try {42 buffer.consume();43 } catch (InterruptedException e) {44 Thread.currentThread().interrupt();45 }46 }47 }, "Consumer");48
49 producer.start();50 consumer.start();51 }52}wait() when the condition is not met. Use notifyAll() after each produce/consume to wake the waiting thread. Use while loops (not if) for all condition checks.16. Common Mistakes
Mistake 1: Calling `start()` Twice on Same Thread
1Thread t = new Thread(() -> System.out.println("hello"));2t.start();3t.start(); // ❌ IllegalThreadStateExceptionFix: Create a new Thread object for each execution.
Mistake 2: Calling `run()` Instead of `start()`
1Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));2t.run(); // prints "main" — runs on the CURRENT thread, not a new one!Fix: Always call start(). It creates the OS thread and then calls run() on the new thread.
Mistake 3: Calling `wait()` Outside Synchronized Block
1obj.wait(); // ❌ IllegalMonitorStateExceptionFix:
1synchronized (obj) {2 obj.wait(); // ✅ correct3}Mistake 4: Using `if` Instead of `while` with `wait()`
1synchronized (obj) {2 if (!condition) obj.wait(); // ❌ vulnerable to spurious wakeup3 doWork(); // may run even if condition is still false4}Fix:
1synchronized (obj) {2 while (!condition) obj.wait(); // ✅ re-checks after every wakeup3 doWork();4}Mistake 5: Using `Thread.stop()` to Stop a Thread
1thread.stop(); // ❌ deprecated — corrupts shared stateFix: Use a volatile boolean flag and cooperative stopping.
Mistake 6: Assuming Thread Execution Order
1t1.start();2t2.start();3// Do NOT assume t1 finishes before t2Fix: Use join() if you need ordering:
1t1.start();2t1.join(); // waits for t1 to finish before proceeding3t2.start();17. Best Practices
- Prefer
Runnableover extendingThread— keeps your class flexible and compatible with thread pools.
- Use lambda expressions for simple runnable tasks to reduce boilerplate.
- Always use
whileloops aroundwait()— neverif.
- Prefer
notifyAll()overnotify()in most cases —notify()wakes only one arbitrary thread, which may not be the right one.notifyAll()is safer.
- Minimize the scope of
synchronized— synchronize only the critical section, not the whole method, to maximize concurrency.
- Never call
Thread.stop(),suspend(), orresume()— use cooperative cancellation withvolatileflags orThread.interrupt().
- Name your threads — makes debugging and log analysis much easier:
1 new Thread(task, "ProducerThread");- Handle
InterruptedExceptionproperly — restore the interrupt flag:
1 catch (InterruptedException e) {2 Thread.currentThread().interrupt(); // restore interrupted status3 }- Consider
java.util.concurrentfor production code —ExecutorService,BlockingQueue,CountDownLatch,Semaphoreetc. are higher-level and less error-prone than rawsynchronized/wait()/notify().
18. Interview Notes
Q1: What are the two ways to create a thread in Java? Which is preferred and why?
Two ways: implements Runnable and extends Thread. Runnable is preferred because a class implementing Runnable can still extend another class (Java allows only single inheritance), can implement multiple interfaces, and works with thread pools/ExecutorService. Extending Thread limits flexibility.
Q2: What is the difference between start() and run()?
start() creates a new OS thread and then calls run() on that new thread. Calling run() directly doesn't create a new thread — it executes run() on the calling thread (same as a normal method call).
Q3: What are the thread states in Java?
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. "RUNNING" is not a separate state — a thread executing code is still technically in RUNNABLE.
Q4: What is a monitor lock? Which object owns it?
Every Java object has one intrinsic (monitor) lock. A synchronized method/block acquires the lock on this (the instance) or on a specified object. Only one thread can hold the lock at a time. When the thread exits the synchronized block, the lock is released.
Q5: What is the difference between BLOCKED and WAITING?
BLOCKED — thread is waiting to acquire a monitor lock held by another thread (automatic transition when lock is released). WAITING — thread explicitly called wait() and is waiting to be notified via notify()/notifyAll(). Both release the monitor lock.
Q6: Does sleep() release the monitor lock?
No. Thread.sleep() puts the thread in TIMED_WAITING but does NOT release any monitor locks. wait() does release the lock.
Q7: Why must wait(), notify(), notifyAll() be called inside a synchronized block?
Because they operate on the object's monitor. If a thread calls wait() without holding the monitor, it can't safely pause execution or guarantee visibility of state changes. The JVM enforces this — calling outside synchronized throws IllegalMonitorStateException.
Q8: What is a spurious wakeup? How do you guard against it?
A spurious wakeup is when a thread wakes from wait() without being notified — allowed by the Java spec due to OS-level signal behavior. Guard against it by checking the wait condition in a while loop, not an if statement, so the thread re-checks and re-waits if the condition is still not met.
Q9: Why are Thread.stop(), suspend(), and resume() deprecated?
stop() forcibly kills the thread and releases all its locks, potentially leaving shared data in an inconsistent state. suspend() pauses the thread while it still holds its locks, causing potential deadlock if another thread tries to acquire those locks. The correct alternative is cooperative stopping using a volatile boolean flag.
Q10: What is the difference between notify() and notifyAll()?
notify() wakes up one arbitrary thread waiting on the object's monitor. notifyAll() wakes up all waiting threads. notifyAll() is generally safer because notify() may wake the wrong thread, leaving the right thread waiting indefinitely.
19. Practice Questions
Easy
- Create a thread using
implements Runnablethat prints numbers 1 to 10. Run it and observe which thread name prints.
- Create the same thread using
extends Thread. Compare the code.
- Create two threads that both print "Hello from Thread X". Run them and observe the interleaving.
- Write a program that demonstrates what happens when you call
run()instead ofstart().
- Demonstrate that a
TERMINATEDthread cannot be restarted (catch the exception).
Medium
- Create two threads sharing a
Counterobject with asynchronized increment()method. Run both threads 1000 times each and verify the final count is always 2000. Then removesynchronizedand observe the inconsistency.
- Write a program where Thread 1 sleeps for 5 seconds inside a
synchronizedblock. Show that Thread 2 cannot enter asynchronizedblock on the same object during those 5 seconds.
- Demonstrate that
synchronizedon different objects does NOT provide mutual exclusion.
- Implement the single-item producer-consumer from the lecture and add proper logging showing thread names and state transitions.
- Write a program with two threads where
wait()andnotify()coordinate them — Thread A prints odd numbers, Thread B prints even numbers, alternating: 1, 2, 3, 4, 5...
Hard
- Implement the full Producer-Consumer with a bounded queue from the assignment (Section 15) using
synchronized,wait(), andnotifyAll().
- Implement a thread-safe Singleton class using the double-checked locking pattern.
- Create a deadlock scenario with two threads and two objects, then identify and fix it.
- Implement a custom thread pool from scratch that manages a fixed number of worker threads and a task queue.
- Implement graceful thread stopping using a
volatileflag andThread.interrupt()correctly, ensuring that a thread blocked insleep()is also interrupted properly.
20. Summary
Revision Bullets:
- Two ways to create a thread:
implements Runnable(preferred) andextends Thread. Runnableis preferred because it doesn't sacrifice single inheritance and works with thread pools.Threadclass itself implementsRunnable. When you pass aRunnabletoThread, it stores it astargetand callstarget.run()inside its ownrun().- Always call
start(), neverrun()directly.start()creates a new OS thread;run()just executes on the current thread. - Thread states:
NEW → RUNNABLE → (BLOCKED/WAITING/TIMED_WAITING) → TERMINATED. - Every object has a monitor lock.
synchronizedblocks/methods acquire this lock. BLOCKED= waiting for another thread's lock.WAITING= calledwait().TIMED_WAITING= calledsleep()orwait(ms).wait()andBLOCKEDboth release the monitor lock.sleep()does NOT release the monitor lock.wait(),notify(),notifyAll()must be called inside asynchronizedblock, orIllegalMonitorStateExceptionis thrown.- Always use
while (!condition) { wait(); }— neverif— to guard against spurious wakeups. notifyAll()is generally safer thannotify().Thread.stop(),suspend(),resume()are deprecated. Usevolatileflags for cooperative stopping.- A terminated thread cannot be restarted — calling
start()on it throwsIllegalThreadStateException.
Mastery check
How well can you recall this?
Finished this lesson?