Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

February 24, 2016 Categories: Multithreading. No Comments on Inter Thread Communication

In this article we will learn how to implement inter thread communication i.e how can we coordinate the communication between two or more threads.

 

Although we can restrict the access of data or code to a single thread at a time by using synchronization, it can’t guarantee the consistent execution of our logic.

 

As an example let’s consider the conventional Producer-Consumer problem which is generally introduced in Operating Systems course. In this problem Producer process or thread produces items and stores in a queue and Consumer process or thread consumes items from the queue. Note that the Consumer thread should wait until the Producer produces at least one item.

 

In our example we will maintain a class Q which contains a single variable n. The Producer thread stores item (integer) into and Consumer thread retrieves the item (integer) from n.

 

Consumer thread must wait until the Producer places an item in n and Producer should wait until the Consumer retrieves the item in n. This kind of inter thread communication can be achieved using the following pre-defined methods in Object class:

final void wait() throws InterruptedException

final void notify()

final void notifyall()

 

Consider the following example Java Program which provides solution to Producer-Consumer problem:

 

Although the put() and get() methods are sychronized, the output of the above program looks like this:

Put: 1

Put: 2

Put: 3

Got: 3

Got: 3

Got: 3

Put: 4

Put: 5

Put: 6

Got: 6

Got: 6

 

To make the Producer wait until Consumer retrieves the item and Consumer wait until Producer places an item, we can use the wait() and notify() methods as shown in the below program:

 

Output of the above program is:

Put: 1

Got: 1

Put: 2

Got: 2

Put: 3

Got: 3

 

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me