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)
1️⃣ start() — Start a New Thread
πΉ Purpose
-
Creates a new call stack
-
Executes code concurrently
πΉ Example
πΉ 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
πΉ Important
Calling run() directly:
❌ Runs like a normal method, NOT a thread
π§ Diagram
3️⃣ sleep() — Pause Current Thread
πΉ Purpose
-
Temporarily pauses execution
-
Does not release lock
πΉ Example
πΉ Diagram
πΉ Use Case
-
Retry logic
-
Polling
-
Rate limiting
4️⃣ join() — Wait for Thread to Finish
πΉ Purpose
-
Makes one thread wait for another to complete
πΉ Example
πΉ Diagram
π 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
πΉ Example
πΉ Diagram
6️⃣ notify() — Wake One Waiting Thread
πΉ Purpose
-
Wakes one thread waiting on the same object
πΉ Example
πΉ Diagram
7️⃣ notifyAll() — Wake All Waiting Threads
πΉ Purpose
-
Wakes all threads waiting on the object
πΉ Example
π wait() vs sleep()
| Feature | wait() | sleep() |
|---|---|---|
| Releases lock | ✅ Yes | ❌ No |
| Needs synchronized | ✅ Yes | ❌ No |
| Wakes by notify | ✅ Yes | ❌ No |
| Used for | Inter-thread communication | Delay |
π notify() vs notifyAll()
| notify() | notifyAll() |
|---|---|
| Wakes one thread | Wakes all threads |
| Risk of starvation | Safer |
| Faster | Slightly slower |
π Best practice: Prefer notifyAll() in complex systems.
8️⃣ Real-World Producer–Consumer Example
π§ Flow Diagram
⚠️ 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()andnotify()enable inter-thread communication and must be used inside synchronized blocks.
π§© When to Use What?
| Scenario | Method |
|---|---|
| Start parallel task | start() |
| Delay execution | sleep() |
| Wait for result | join() |
| Thread coordination | wait / notify |
| Multiple waiting threads | notifyAll |
π 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