/** This class demonstrates race condition. It needs the Depositer and Withdrawer classes. */ public class Account { private int balance; private boolean depositFlag; private boolean withdrawFlag; public Account(int startBalance) { balance = startBalance; stopDeposit(); stopWithdraw(); } public void startDeposit() { depositFlag = true; } public void startWithdraw() { withdrawFlag = true; } public boolean isDepositing() { return depositFlag; } public boolean isWithdrawing() { return withdrawFlag; } public void stopDeposit() { depositFlag = false; } public void stopWithdraw() { withdrawFlag = false; } public /* synchronized */ void deposit(int amount) { /* balance += amount; */ int b = balance; try { Thread.sleep((int) (Math.random()*10)); balance = b + amount; } catch (Exception e) {}; } public /* synchronized */ void withdraw(int amount) { /* balance -= amount; */ int b = balance; try { Thread.sleep((int) (Math.random()*10)); balance = b - amount; } catch (Exception e) {}; } public void showBalance() { System.out.print("$" + balance); } public static void main(String[] args) { Account ac = new Account(10000); System.out.print("Begining balance: "); ac.showBalance(); System.out.println(); Depositer d = new Depositer(ac); Withdrawer w = new Withdrawer(ac); d.start(); w.start(); while (ac.isDepositing() || ac.isWithdrawing()) { try { Thread.sleep(10); } catch (Exception e) {}; } System.out.print("Ending balance: "); ac.showBalance(); System.out.println(); } }