How to make threads communicate with each other in java programming

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/05/make-threads-communicate-java-programming/

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

 

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/05/make-threads-communicate-java-programming/

2 Comments

  1. Word WinngHacker 2017-06-18 Reply

Add a Comment

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

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger