// concurrent banking - base program for problem 2 of 1st assignment. // simple class for bank account objects: class account { private double balance; // account balance public account(double b) {balance=b;} // constructor sets initial balance public double inquiry() { return balance; } // balance inquiry public void deposit(double amt) { if (amt>0) balance += amt; } public void withdraw(double amt) { if (amt<=balance) balance -= amt; else System.out.println("not enough funds"); } }//account // Each owner of the account is represented by a thread: class accountuser // superclass for all account user threads { protected account A; // pointer to shared account public accountuser(account A) {this.A=A;} protected void printbalance() { System.out.printf("The balance is now %.2f\n", A.inquiry()); System.out.flush(); // force immediate printing (dont' buffer) } protected void delay1sec() // simulated one second delay { try {Thread.sleep(1000);} catch(InterruptedException e){} } }// accountuser superclass // spender thread: class spender extends accountuser implements Runnable { int n; // controls length of loop public spender(account A, int m) { super(A); n=m; } // constructor public void run() { while (n-- > 0) { double amount = Math.random()*1000; // spend up to $1000 amount = ((int)(amount*100+.5))/100.0; // round off to cents A.withdraw(amount); // love to spend! }//while printbalance(); }//run }// spender // earner thread: class earner extends accountuser implements Runnable { public earner(account A) { super(A); } // constructor public void run() { A.deposit(100); delay1sec(); A.deposit(200); delay1sec(); A.deposit(400); delay1sec(); A.deposit(800); delay1sec(); A.deposit(1600); // the more I earn the more they spend ... printbalance(); }//run }// earner // main thread for testing. public class banking { public static void main(String[] args) throws Exception { account checking = new account(100); // create account Thread earn = new Thread(new earner(checking)); Thread spend = new Thread(new spender(checking,20)); Thread spendmore = new Thread(new spender(checking,10)); earn.start(); spend.start(); spendmore.start(); earn.join(); spend.join(); // spend.interrupt(); will interrupt waiting threads spendmore.join(); System.exit(0); }// main }