wait() -causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object
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.
class student extends Thread {
int amount = 1000;
void withdraw ( int amount ) {
synchronized (this) {
System.out.println("Withdrawing..." + amount);
if (this.amount < amount) {
System.out.println("Low balance...." + this.amount);
try {
wait();
} catch (Exception e) {
}
}//if ends
this.amount = this.amount - amount;
System.out.println("withdraw completed " + amount);
System.out.println("Balance" + this.amount);
}
}
synchronized void deposit ( int amount ) {
System.out.println("going to deposit..." + amount);
this.amount = this.amount + amount;
System.out.println("update balance deposit completed... " + this.amount);
notify();
}
} // student ends
class interth {
public static void main ( String[] args ) {
student s = new student();
new Thread() {
public void run () {
s.withdraw(1500);
}
}.start();
new Thread() {
public void run () {
s.deposit(1000);
}
}.start();
}
}
Output:
Withdrawing...1500
Low balance....1000
going to deposit...1000
update balance deposit completed... 2000
withdraw completed 1500
Balance500
No comments:
Post a Comment