Interthread Communication


Interthread Communication

Inter-thread communication uses wait and notify methods i.e. if one thread wants to tell something to another thread, it uses wait (), notify(), and notifyAll() method of java.lang.Object. The methods are declared as final. Since it throws a checked exception, we must use these methods within Java try-catch block.

Syntax for wait method:

public final void wait()

Syntax for notify method:

public final void notify()

Syntax for notifyAll method:

public final void notifyAll()

Thread Pooling:

The most common way to create pooling is to use a loop, which checks a condition repeatedly. The necessary action is executed once the condition is true. This is a waste of CPU resources. We use java inter-thread communication to address this problem.

A description on methods of java inter thread communication:

  • wait() method: Causes the current thread to relinquish the lock and wait until another thread calls the notify() or notifyAll() methods on this object, or until a certain period has passed. The current thread must own this object's monitor; therefore, it can only be called from the synchronized method; otherwise, it will throw an error.
  • notify() method: This method wakes up a single thread that is waiting on the monitor of this object. If this object has any waiting threads, one of them is picked to be awakened. The decision is arbitrary and made at the implementation's discretion.
  • notifyAll() method: All threads waiting on this object's monitor are woken up.

Example:

Com.knowledge2life class Customer{ int amount=10000; synchronized void withdraw(int amount){ System.out.println("going to withdraw..."); if(this.amount<amount){ System.out.println("Less balance; waiting for deposit..."); try{wait();}catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount){ System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } class Test{ public static void main(String args[]){ final Customer c=new Customer(); new Thread(){ public void run(){c.withdraw(15000);} }.start(); new Thread(){ public void run(){c.deposit(10000);} }.start(); } }

OUTPUT:

going to withdraw…
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...