Synchronization
: Lesson 04 – Cooperation / Inter Thread Communication
Communication
between synchronized Threads known as Cooperation ( Inter Thread
Communication ).
Cooperation
is a mechanism in which a thread is paused in its critical section
and another thread is allowed to enter ( or lock ) in the same
critical section to be executed.
- wait()
- notify()
- notifyAll()
wait()
The
thread will wait until it has been notified that it can proceed to
act.
The
wait() method can take an optional timeout value as a parameter.
If
this value is used, it means that the thread will either wait until
it's notified or it will continue to execute once the timeout value
has passed.
- wait()
- wait(long timeout)
notify()
Wake
up a single thread which is waiting on this object's monitor.
notifyAll()
Wakes
up all the threads which are waiting on this object's monitor.
1.
BankATM.java
public
class
BankATM {
double
balance =
10000D;
synchronized
boolean
withdraw(boolean
status, double
amount){
System.out.println("going
to withdraw ...");
if(balance
> amount){
System.out.println("less
than the daily amount ...");
try{
wait();
}catch
(Exception e) {
//
TODO:
handle exception
}
this.balance
-= amount;
status
= true;
System.out.println("withdraw
completed");
}
return
status;
}
synchronized
void
deposit(double
amount){
System.out.println("Going
to Deposit");
this.balance
+= amount;
System.out.println("Deposit
completed ,,, ");
notify();
}
synchronized
double
checkBalanace(){
System.out.println("Checking
balance ...");
notify();
return
this.balance;
}
}
2.Customer.java
public
class
Customer {
/**
* @param
args
*/
public
static
void
main(String[] args) {
Customer
customer = new
Customer();
customer.execute();
}
private
void
execute(){
final
BankATM bankATM = new
BankATM();
Thread
withDrawThread = new
Thread(){
public
void
run(){
boolean
status = bankATM.withdraw(false,
5000);
if(status){
System.out.println("Withdraw
is Success.");
}else{
System.out.println("Withdraw
is Fail.");
}
}
};
Thread
depositThread = new
Thread(){
public
void
run(){
bankATM.deposit(2500);
System.out.println("Deposit
done");
}
};
Thread
checkAfterBalanceThread = new
Thread(){
public
void
run(){
double
balance = bankATM.checkBalanace();
System.out.println("The
New balance is " + balance);
}
};
withDrawThread.start();
depositThread.start();
checkAfterBalanceThread.start();
}
}
Output
going
to withdraw ...
less
than the daily amount ...
Going
to Deposit
Deposit
completed ,,,
withdraw
completed
Withdraw
is Success.
Deposit
done
Checking
balance ...
The
New balance is 7500.0