Nearby lessons

75 of 125

Java - Inter-thread Communication

📌 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

Inter-thread Communication is a core concept of the Java language. This lesson explains Thread Communication — wait() and notify() with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Thread Communication — wait() and notify()

Sometimes one thread must wait for another thread to do something. For example, a Producer thread makes an item and a Consumer thread uses it.

  • wait() — the current thread gives up the lock and sleeps until someone calls notify().
  • notify() — wakes up one waiting thread.
  • notifyAll() — wakes up all waiting threads.

These three methods can be called only inside a synchronized block (because they need the lock).

Example01
JCode Cell
1class Shared {
2 int item;
3 boolean available = false;
4 
5 synchronized void produce(int v) throws InterruptedException {
6 while (available) wait(); // wait until consumer takes it
7 item = v; available = true;
8 notify();
9 }
10 synchronized int consume() throws InterruptedException {
11 while (!available) wait(); // wait until producer gives it
12 available = false; notify();
13 return item;
14 }
15}
📝 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 Questions
Progress: 0 / 1