Java program to demonstrate Inter-Thread Communication

Hey there!

Welcome to

In this post, we will look at a Java program to demonstrate Inter-Thread Communication. I would suggest you go through the below link before proceeding with this post.

Core Java program to create multiple threads

Inter-Thread communication is an important aspect in a multi-threaded environment. Java provides this facility using below three methods defined in Object class:

  1. wait(): Immediately releases the lock on the object and waits for acquiring the lock 
  2. notify(): Notifies the waiting Thread and releases the lock(may not release the lock immediately)
  3. notifyAll(): Notifies the all waiting Threads and releases the lock(may not release the lock immediately)

We will consider a scenario where there are three Threads in which one will generate a random number every second. The second thread prints its square value if the random number is an even number. The third thread will print the cube value if the random number is an odd number.

Here is the simple random number generator class:


Let’s look at the program for implementing the above-mentioned scenario:


If the Random number is even, it’s square is printed by Square Printer thread and if it is odd, it’s cube is printed by Cube Printer thread. The inter-thread communication is dependent on how we call wait(), notify() and notifyAll() to proceed with the execution.

Happy Learning :).

Please leave a reply in case of any queries.

Leave a Reply

Your email address will not be published. Required fields are marked *