1 // Purpose. wait() and notifyAll() demo 2 class Account { 3 private int balance = 0; 4 public synchronized void deposit( int a ) { 5 balance += a; 6 System.out.println( "balance increased by " + a ); 7 notifyAll(); 8 } 9 public synchronized void withdraw( int a ) { 10 while (balance < a) { 11 System.out.println( "withdraw " + a + " waiting" ); 12 try { wait(); } catch(InterruptedException e) { } 13 } 14 balance -= a; 15 System.out.println( "balance decreased by " + a ); 16 } } 17 class AccountUpdate extends Thread { 18 private Account acct; 19 private int amt; 20 public AccountUpdate( Account a, int i ) { 21 acct = a; amt = i; 22 } 23 public void run() { 24 if (amt > 0) acct.deposit( amt ); 25 else acct.withdraw( -amt ); 26 } } 27 public class ThreadWithdraw { 28 public static void main( String argv[] ) { 29 Account acct = new Account(); 30 new AccountUpdate( acct, -20 ).start(); 31 new AccountUpdate( acct, 10 ).start(); 32 try { Thread.sleep(100); } catch (Exception e) { } 33 new AccountUpdate( acct, -40 ).start(); 34 new AccountUpdate( acct, 20 ).start(); 35 try { Thread.sleep(100); } catch (Exception e) { } 36 new AccountUpdate( acct, 30 ).start(); 37 } } 38 // withdraw 20 waiting 39 // balance increased by 10 40 // withdraw 20 waiting 41 // withdraw 40 waiting 42 // balance increased by 20 43 // balance decreased by 20 44 // withdraw 40 waiting 45 // balance increased by 30 46 // balance decreased by 40