1 class Account { 2 private int balance = 100; 3 public void updateBalance( int a ) { 4 System.out.println( "get " + a ); 5 int b = balance; 6 try { Thread.sleep(10); } catch (Exception e) { } 7 System.out.println( "set " + a ); 8 balance = b + a; 9 } 10 public int getBalance() { 11 return balance; 12 } } 13 class AccountUpdate extends Thread { 14 private Account acct; 15 private int amt; 16 public AccountUpdate( Account a, int i ) { 17 acct = a; amt = i; 18 } 19 public void run() { 20 acct.updateBalance( amt ); 21 } } 22 public class ThreadAccount { 23 public static void main( String[] args ) { 24 Account acct = new Account(); 25 new AccountUpdate( acct, 20 ).start(); 26 new AccountUpdate( acct, -10 ).start(); 27 try { Thread.sleep( 100 ); } catch (Exception e) { } 28 System.out.println( "balance is " + acct.getBalance() ); 29 } } 30 // get 20 31 // get -10 32 // set 20 33 // set -10 34 // balance is 90 3 public synchronized void updateBalance( int a ) { 30 // get 20 31 // set 20 32 // get -10 33 // set -10 34 // balance is 110