Java Thread Methods Explained (start, run, join, wait, notify…)

 

Java Thread Methods Explained (start, run, join, wait, notify…)

πŸ“Œ What is a Thread in Java?

A thread is a lightweight unit of execution inside a Java program.
Java supports multithreading, allowing multiple tasks to run concurrently.


🧭 Java Thread Lifecycle (Text Diagram)

┌──────────┐ │ NEW │ ← Thread object created └────┬─────┘ │ start() ▼ ┌──────────┐ │ RUNNABLE │ ← Ready / Running └────┬─────┘ │ sleep(), wait(), join() ▼ ┌──────────┐ │ WAITING │ │ /BLOCKED │ └────┬─────┘ │ notify(), timeout over ▼ ┌──────────┐ │ RUNNABLE │ └────┬─────┘ │ run() completes ▼ ┌──────────┐ │ TERMINATED│ └──────────┘

1️⃣ start() — Start a New Thread

πŸ”Ή Purpose

  • Creates a new call stack

  • Executes code concurrently

πŸ”Ή Example

Thread t = new Thread(() -> { System.out.println("Thread running"); }); t.start();

πŸ”Ή Key Point

✔️ start() calls run() internally
❌ Never call start() twice (IllegalThreadStateException)


πŸ“Œ Interview Tip

start() creates a new thread, run() does not.


2️⃣ run() — Thread Execution Logic

πŸ”Ή Purpose

  • Contains the business logic of the thread

πŸ”Ή Example

public void run() { System.out.println("Inside run()"); }

πŸ”Ή Important

Calling run() directly:

t.run();

❌ Runs like a normal method, NOT a thread


🧠 Diagram

main thread | └── run() ❌ (no new thread)

3️⃣ sleep() — Pause Current Thread

πŸ”Ή Purpose

  • Temporarily pauses execution

  • Does not release lock

πŸ”Ή Example

Thread.sleep(1000); // 1 second

πŸ”Ή Diagram

RUNNING → sleep(1s) → RUNNABLE

πŸ”Ή Use Case

  • Retry logic

  • Polling

  • Rate limiting


4️⃣ join() — Wait for Thread to Finish

πŸ”Ή Purpose

  • Makes one thread wait for another to complete

πŸ”Ή Example

Thread t = new Thread(() -> { System.out.println("Worker thread"); }); t.start(); t.join(); System.out.println("Main thread resumes");

πŸ”Ή Diagram

Main Thread | ├── start Worker | └── join() → WAIT | ▼ Worker finishes | ▼ Main resumes

πŸ“Œ Real-World Use

  • Parallel tasks

  • Batch processing

  • Result aggregation


5️⃣ wait() — Release Lock and Wait

πŸ”Ή Purpose

  • Makes thread wait until notified

  • Releases monitor (lock)

πŸ”Ή Must Be Called Inside

synchronized(obj) { ... }

πŸ”Ή Example

synchronized(lock) { lock.wait(); }

πŸ”Ή Diagram

Thread A (holds lock) | └── wait() ↓ releases lock ↓ WAITING

6️⃣ notify() — Wake One Waiting Thread

πŸ”Ή Purpose

  • Wakes one thread waiting on the same object

πŸ”Ή Example

synchronized(lock) { lock.notify(); }

πŸ”Ή Diagram

WAITING Threads | └── notify() → one thread wakes up

7️⃣ notifyAll() — Wake All Waiting Threads

πŸ”Ή Purpose

  • Wakes all threads waiting on the object

πŸ”Ή Example

synchronized(lock) { lock.notifyAll(); }

πŸ”„ wait() vs sleep()

Featurewait()sleep()
Releases lock✅ Yes❌ No
Needs synchronized✅ Yes❌ No
Wakes by notify✅ Yes❌ No
Used forInter-thread communicationDelay

πŸ”„ notify() vs notifyAll()

notify()notifyAll()
Wakes one threadWakes all threads
Risk of starvationSafer
FasterSlightly slower

πŸ“Œ Best practice: Prefer notifyAll() in complex systems.


8️⃣ Real-World Producer–Consumer Example

class Shared { boolean dataReady = false; synchronized void produce() throws InterruptedException { while (dataReady) wait(); System.out.println("Producing data"); dataReady = true; notifyAll(); } synchronized void consume() throws InterruptedException { while (!dataReady) wait(); System.out.println("Consuming data"); dataReady = false; notifyAll(); } }

🧠 Flow Diagram

Producer → produce() → notify() Consumer → wait() → consume()

⚠️ Common Mistakes (Interview Favorite)

❌ Calling wait() without synchronized
❌ Calling run() instead of start()
❌ Using notify() instead of notifyAll()
❌ Sleeping while holding locks


🧠 Interview 30-Second Summary

start() creates a new thread, run() contains logic.
sleep() pauses without releasing locks.
join() waits for thread completion.
wait() and notify() enable inter-thread communication and must be used inside synchronized blocks.


🧩 When to Use What?

ScenarioMethod
Start parallel taskstart()
Delay executionsleep()
Wait for resultjoin()
Thread coordinationwait / notify
Multiple waiting threadsnotifyAll

πŸ”‘ Final Takeaway

Java threading is powerful but dangerous if misused.
Modern Java often prefers:

  • ExecutorService

  • CompletableFuture

  • ForkJoinPool

…but interviews still expect core thread knowledge.

No comments:

Post a Comment

Java Thread Methods Explained (start, run, join, wait, notify…)

  Java Thread Methods Explained (start, run, join, wait, notify…) πŸ“Œ What is a Thread in Java? A thread is a lightweight unit of executio...

Featured Posts