Nearby lessons
76 of 125Java - Deadlock
📌 What You Will Learn
- What a thread is and how it is different from a process
- Two ways to create a thread: Thread class and Runnable interface
- The thread life cycle (states)
- How threads cooperate: synchronized, wait and notify
- The modern way: Executors, Callable and lambdas
Deadlock is a core concept of the Java language. This lesson explains Deadlock — The Dangerous Trap with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Deadlock — The Dangerous Trap
Deadlock happens when two threads are each waiting for a lock that the other thread holds. Neither can move, and the program hangs forever.
How to avoid deadlock: keep a fixed order of locking (everyone takes locks in the same sequence), avoid holding a lock while waiting for another, and use tryLock() with timeouts instead of plain locks.
In simple words: Deadlock is two threads each holding a lock and waiting for the other's lock. Neither can proceed, so the program hangs forever — prevent it by taking locks in a consistent order.
Example01
📝 Key Takeaways
- A thread is a small unit of work; a process is a running program.
- Create a thread by extending Thread or (better) implementing Runnable.
- Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
- Shared data races when many threads change it; synchronized gives a lock.
- wait/notify let threads talk; they need the lock.
- Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
- Real projects use Executors + Callable instead of raw threads.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1