// Simulates race condition on threads in Java // The only reason Account has to be called as an extension of Thread is // because it calls "sleep". class Account extends Thread { int value; String Name; Account(String N) { value = 0; Name=N; } // constructor public void run() { for (;;) {} } public void deposit(int M) { int temp = value; System.out.println(Name + " accepting deposit " + M); try { // simulates long computation or I/O Thread.currentThread().sleep(100); } catch(InterruptedException ie) {} value = temp+M; System.out.println(Name + " deposit accepted: New value " + value); } } class Depositor extends Thread { Account[] accountList; // sequence of accounts to deposit to int[] amountList; // sequence of amounts to deposit Depositor(Account[] accs, int[] al) { // constructor accountList = accs; amountList = al; } public void run() { for (int i=0; i < accountList.length; i++) accountList[i].deposit(amountList[i]); } } // creates three accounts and three depositors, who deposit various amounts // to the accounts. public class race { public static Account savings = new Account("Savings"); public static Depositor fred = new Depositor( new Account[] {savings}, new int[] {1}); public static Depositor gina = new Depositor( new Account[] {savings}, new int[] {10}); public static void main (String s[]) { fred.start(); gina.start(); } }