When two or more thread needs to exchange information between them in an application, Inter-thread communication is required. Hence, we can also call it Co-Operation.
The methods that are used for this communication are:
- wait()
- notify()
- notifyAll()
1. wait()
This method is written as:
1 | public void wait() |
This causes the current thread to wait until another thread invokes the notify() method that is it waits until the object is notified.
2. notify()
This method is written as:
1 | public void notify() |
This method wakes up a single thread that is waiting on this object’s monitor.
3. notifyAll()
This method is written as:
1 | public void notifyAll() |
This method wakes up all the threads that called wait( ) on the same object.
Example: Java program to illustrate the Inter-Thread Communication:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | class Bank { int cash = 500; synchronized void cashWithdraw(int cash) { System.out.println("Going to withdraw Cash"); if(this.cash < cash) { System.out.println("Not Enough Balance"); try{ wait(); //wait method }catch(Exception e) { } } this.cash -= cash; System.out.println("Cash Withdrawal Completed"); } synchronized void cashDeposit(int cash) { System.out.println("Processing Deposit"); this.cash += cash; System.out.println("Deposit completed"); notify(); //notify method } } public class Main { public static void main(String args[]) { final Bank b = new Bank(); new Thread() { public void run() { b.cashWithdraw(1000); } }.start(); new Thread() { public void run() { b.cashDeposit(10000); } }.start(); } } |
Output:
1 2 3 4 5 | Going to withdraw Cash Not Enough Balance Processing Deposit Deposit completed Cash Withdrawal Completed |