public class Customer {
int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("going to
withdraw..." + amount); //Synchronized Method
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... now balance is " + this.amount);
}
synchronized void deposit(int amount) {
System.out.println("going to
deposit... " + amount );
this.amount += amount;
System.out.println("deposit
completed... now balance is " + this.amount);
notify();
}
void printBalance() {
System.out.println("Current balance
: " + this.amount);
}
public static void main(String args[]) {
final Customer c = new Customer();
c.printBalance();
new Thread() {
public void run() {
c.withdraw(15000);
}
}.start();
new Thread() {
public void run() {
c.deposit(11000);
}
}.start();
}
}
Current balance : 10000
going to withdraw...15000
Less balance; waiting for deposit...
going to deposit... 11000
deposit completed... now balance is 21000
withdraw completed... now balance is 6000