Inter Thread Communication is one of the distinct facility in multi threading application development of java. Inter thread communication concept is one of the specialized form of inter process communication of operating system. In real world Inter Thread communication based applications of java very fastest applications compared to all the applications in java.

Cooperation(Inter-thread communication) is all about making synchronized threads communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:

  • wait()
  • notify()
  • notifyAll()
  1. wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor and call notify. Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object’s monitor.                                         Syntax:
    public final void wait() throws InterruptedException
    public final void wait(long timeout)throws InterruptedException
    
  2. notify() wakes up a thread that called wait() on same object. Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
    Syntax:
    public final void notify()
    
  3. notifyAll() wakes up all the thread that called wait() on same object. Wakes up all threads that are waiting on this object’s monitor.
    public final void notifyAll()
    

Difference between wait() and sleep()

wait() sleep()
called from synchronized block no such requirement
monitor is released monitor is not released
awake when notify() or notifyAll() method is called. not awake when notify() or notifyAll() method is called
not a static method static method
wait() is generally used on condition sleep() method is simply used to put your thread on sleep.

Thread Pooling

Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition is true appropriate action is taken. This waste CPU time.

Deadlock:
Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.

Example of Inter thread Communication:

class Customer {
   int amount=0;
   int flag=0;
   public synchronized int withdraw(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to withdraw");
 
       if(flag==0){
           try{
  System.out.println("waiting....");
  wait();
      }catch(Exception e){}
 }
 this.amount-=amount;
 System.out.println("withdraw completed");
 return amount;
     }

     public synchronized void deposit(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to  deposit");
 this.amount+=amount;
 System.out.println("deposit completed");
        notifyAll();
        flag=1;
    }
 }

public class SyncThreadDemo {
    public static void main(String[] args) {
 final Customer c = new Customer();
 
 Thread t1 = new Thread(){
  public void run(){
   c.withdraw(5000);
   System.out.println("After withdraw amount is "+c.amount);
                        
  }
   };
 
 Thread t2 = new Thread(){
  public void run(){
   c.deposit(9000);
   System.out.println("After deposit amount is "+c.amount);
  }
    };

 t1.setName("Dinesh");
        t2.setName("Sweety");
 t1.start();
 t2.start();

    }
}

Output:

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago