Inter-thread communication or Co-operation is all about allowing synchronized threads to 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() method

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.

2)  notify() method

Wakes up a single thread that is waiting. If any threads are waiting on this object, one of them is chosen to be awakened.

3)  notifyAll() method

Wakes up all threads that are waiting.

class AThread{

int amount=10000;

synchronized void withdraw(int amt) {

System.out.println("Going to Withdraw...");

if(amount<amt) {

System.out.println("Less balance; waiting for deposit...");

try {

wait();

} catch (Exception e) { System.out.println(e);

}

}

amount-=amt;

System.out.println("Withdraw Completed with Rs. "+amt); System.out.println("Balance is Rs. "+amount);

}

 

synchronized void deposit(int amt) { System.out.println("Going to Deposit..."); amount+=amt;

System.out.println("Deposit Completed with Rs. "+amt); System.out.println("Balance is Rs. "+amount); notify();

}

}

 

public class Synchronization{

public static void main(String[] args) { AThread obj=new AThread();

 

new Thread() {

public void run() { obj.withdraw(15000);

}

}.start();

 

new Thread() {

public void run() { obj.deposit(10000);

}

}.start();

}

}

Output

Going to Withdraw...

Less balance; waiting for deposit...

Going to Deposit...

Deposit Completed with Rs. 10000

Balance is Rs. 20000

Withdraw Completed with Rs. 15000

Balance is Rs. 5000