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:
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:
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:
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:
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:
Going to withdraw Cash
Not Enough Balance
Processing Deposit
Deposit completed
Cash Withdrawal Completed