11: Threads performing tasks by talking to each other

Q. Given the following code

Output:

Complete the above code so that it prints a=1 and b=1 interleaved.

A. The solution is to have inter thread communication between both threads. One thread executes the method workOnX() on the shared object “SharedObject”, and the other thread invokes “workOnY()

Key Points:

1) The java.lang.Object class the wait()/notify()/notifyAll() methods to communicate among threads via an object with a lock.

2) When using wait/notify the object on which these methods are invoked needs to be synchronized.

The SharedObject changes are shown below

Java Inter Thread Communication using notify/wait

Java Inter Thread Communication using notify/wait

Is there a way to do it using a BlockingQueue?

A BlockingQueue is used to have one thread produce objects, which another thread consumes. The producing thread will keep producing new objects and insert them into the queue, until the queue reaches some upper bound, which will be just 1 here. If the blocking queue reaches its upper limit, the producing thread is blocked while trying to insert the new object. The consuming thread keeps taking objects out of the blocking queue, and processes them. If the consuming thread tries to take an object out of an empty queue, the consuming thread is blocked until a producing thread puts an object into the queue.

Let’s use two blocking queues to communicate with each other.

The above code can be depicted with the diagram shown below.

Using a BlockingQueue data structure

Using a BlockingQueue data structure

More on inter thread communication

6 popular Java multi-threading interview questions and answers with diagrams and code.


Java & Big Data Interview FAQs

Java Key Areas Interview Q&As

800+ Java Interview Q&As

Java & Big Data Tutorials

Top