// Mutual exclusion 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 synchronized void deposit(int M) { System.out.println(Name + " accepting deposit " + M); value = value+M; try { Thread.currentThread().sleep(100); } catch(InterruptedException ie) {} 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 bank { public static Account savings = new Account("Savings"); public static Account checking = new Account("Checking"); public static Account cayman = new Account("Cayman"); public static Depositor fred = new Depositor( new Account[] {savings, checking, cayman}, new int[] {1,2,1000}); public static Depositor gina = new Depositor( new Account[] {checking, checking, savings}, new int[] {10,20,5}); public static Depositor hilda= new Depositor( new Account[] {savings, cayman, savings}, new int[] {100, 2000, 200}); public static void main (String s[]) { fred.start(); gina.start(); hilda.start(); } }