Interthread Communication In Java Example
Chapter:
Thread
Last Updated:
19-08-2017 08:34:38 UTC
Program:
/* ............... START ............... */
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();
}
}
public class JavaInterThreadCommunication {
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();
}
}
/* ............... END ............... */
Output
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
Notes:
-
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.
- If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
- public void wait() - Causes the current thread to wait until another thread invokes the notify().
- public void notify() - Wakes up a single thread that is waiting on this object's monitor.
- public void notifyAll() - Wakes up all the threads that called wait( ) on the same object.
Tags
Interthread communication, Thread, Java