Nearby lessons
74 of 125Java - Synchronization
📌 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
Synchronization is a core concept of the Java language. This lesson explains The Problem — Race Condition and The Solution — synchronized with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
The Problem — Race Condition
When two threads change the same shared variable at the same time, the result can be wrong. This problem is called a race condition. Example: two threads add money to the same account, but the additions get lost.
Example01
The Solution — synchronized
The synchronized keyword gives a lock. Only one thread at a time can enter a synchronized method or block. Others must wait outside until the lock is free.
In simple words: `synchronized` gives a lock so only one thread can enter the method at a time. The other threads wait outside until the lock is free, which fixes the race condition on shared data.
Example02
📝 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