Why do threads communicate?

There are 2 reasons why threads communicate.
  • To work collaboratively by sharing the work
  • To protect shared resources

For protecting shared resources why Threads need to communicate?

  1. In multiprocessing, multiple threads access the same piece of code, sometimes the same reference also. 
  2. To protect the shared reference from concurrent access by multiple threads, threads need to communicate with each other. This is to ensure the reference is accessed by a single thread at any given point of time. 
  3. Single access to a shared resource is achieved by protecting the shared resource with the Synchronized keyword or Lock API(from Java 1.5).
Synchronized block main usage is to restrict the concurrent access to a shared resource from multiple threads. It acts as a barrier by permitting one thread at a time to access the shared resource. It's heavily used in multi-threaded environments where shared references need to be protected from multiple thread access.

In this example, multiple access to the share reference queue is restricted with the help of Synchronized(queue). Since the queue is shared across THREAD-1 and THREAD-2 threads, they use that queue for their communication. By doing this they not only protect the state of shared reference and also resolving the thread acquisition among themselves.

THREAD-2 has to wait till THREAD-1 finishes its task with respect to queue reference.


public class ThreadCommunication {

    public static void main(String[] args) throws InterruptedException{

        Queue<Integer> queue = new LinkedList<>();//Queue is share by THREAD-1 & THREAD-2

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" will take its own time to complete the task");
            synchronized (queue) {
try { Thread.sleep(1000); //Let me sleep for sometime: THREAD-1 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" added element to the pool"); queue.add(new Random().nextInt()); } }, "THREAD-1").start(); Thread.sleep(20); new Thread(()-> {// THREAD-2 has to wait till THREAD-1's queue access is finished System.out.println(Thread.currentThread().getName()+" is waiting for lock on the queue"); synchronized (queue) { queue.poll(); } System.out.println(Thread.currentThread().getName()+" finally consumed the element from the pool"); },"THREAD-2").start(); } } Output
THREAD-1 will take its own time to complete the task
THREAD-2 is waiting for lock on the queue
THREAD-1 added element to the pool
THREAD-2 finally consumed the element from the pool

Comments

Popular posts from this blog

Distributed database design using CAP theorem

LDAP - Basics

Easy approach to work with files in Java - Java NIO(New input output)