// AccountDemo1.java // by Mark Weiss, Fall 2002 // WithdrawThread throws an exception for insufficient funds. // Uses the synchronized keyword to create monitors. class OverdraftException extends Exception { public OverdraftException( ) { } public OverdraftException( String msg ) { super( msg ); } } class Account { public void deposit( int d ) { synchronized( this ) // monitor { balance += d; } } public void withdraw( int d ) throws OverdraftException { synchronized( this ) // monitor { if( balance < d ) throw new OverdraftException( "Overdraft attempting to withdraw " + d ); balance -= d; } } private int balance = 0; } class WithdrawThread extends Thread { private int amount; private Account acc; public WithdrawThread( Account a, int d ) { amount = d; acc = a; } public void run( ) { try { acc.withdraw( amount ); System.out.println( "Withdrew " + amount ); } catch( OverdraftException e ) { System.out.println( e.getMessage( ) ); } } } class DepositThread extends Thread { private int amount; private Account acc; public DepositThread( Account a, int d ) { amount = d; acc = a; } public void run( ) { acc.deposit( amount ); System.out.println( "Deposited " + amount ); } } class AccountDemo1 { public static void main( String [] args ) { Account acc = new Account( ); Thread t1 = new WithdrawThread( acc, 100 ); Thread t2 = new WithdrawThread( acc, 75 ); Thread t3 = new WithdrawThread( acc, 25 ); Thread t4 = new DepositThread( acc, 200 ); // Threads t1, t2, and t3 interrupt t4. By // default, they each have a higher priority: //t4.setPriority( Thread.MIN_PRIORITY ); // If the preceding line is disabled, thread t4 runs // to completion before thread t1 starts. There is no overdraft. t4.start( ); t1.start( ); t2.start( ); t3.start( ); } }