Inter-thread communication
Inter-thread communication is all about making synchronized threads communicate with each other. It 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:
1. wait()
2. notify()
3. notifyAll()
1. wait()
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.
2. notify()
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 threads that are waiting on this object’s monitor.
public final void notifyAll()
Example as follows :
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; notifyAll(); System.out.println("deposit completed"); flag = 1; } } public class SynMethod { 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.start(); t2.start(); } }