Java

Inter-Thread Communication in Java: Producer-Consumer Problem Explained with Examples

When I first started learning about Java multithreading, one of the concepts that took me the longest to grasp was how threads can communicate with each other. Sure, I understood synchronized blocks and how they help prevent race conditions—but I still didn’t know how to make one thread wait for another to finish a task or notify it when to continue.

In this article, I’ll walk you through inter-thread communication in Java using the Producer-Consumer problem, one of the most common and beginner-friendly examples.


🧠 What Is Inter-Thread Communication?




In a multi-threaded application, threads often need to coordinate their actions. Imagine a scenario where one thread produces data, and another consumes it. If the consumer tries to read data before it’s produced, we’ll get inconsistent or incorrect results.

Java provides built-in methods to help threads wait for certain conditions or notify others when they’re ready to proceed. These are:

These methods are available to every object because they come from the Object class, and they must be used inside a synchronized block.


🧪 The Producer-Consumer Problem

Let me show you this with the classic Producer-Consumer problem:

  • The Producer creates items (e.g., integers) and adds them to a shared object.
  • The Consumer takes items from that shared object.
  • The Consumer must wait until there is something to consume.
  • The Producer must wait until the previous item is consumed.

🔧 Step 1: Without wait/notify (Incorrect Version)

When I first tried solving this, I used only synchronized methods:

Producer and Consumer:

And the main driver class:

❌ Problem:

This code runs, but you’ll see output like this:

The Consumer ends up reading the same value multiple times or missing some entirely. This is because there’s no real synchronization on data availability—just mutual exclusion on the methods.


✅ Step 2: Using wait() and notify() (Correct Version)

Now let’s fix it using wait() and notify():

The Producer, Consumer, and Driver classes remain the same.

✅ Output:

Leave a Comment