4

Click here to load reader

Bank Account Sync

Embed Size (px)

Citation preview

Page 1: Bank Account Sync

package BankAccountTesterTrial2;

public class BankAccountTester {/* * Creates and runs threads for depositing and withdrawing to and from * a bank account. * @param args unused */

public static void main(String [] args){

BankAccount account = new BankAccount();for ( int i = 0; i < 5; ++i){

DepositAgent r0 = new DepositAgent(account,100);Thread t0 = new Thread(r0);WithdrawAgent r1 = new WithdrawAgent(account,200);Thread t1 = new Thread(r1);t0.start();t1.start();

}

System.out.println("Final balance: " + account.getBalance());}

}

__________________________________________________________________________________

package BankAccountTesterTrial2;

public class BankAccount {

// A bank account has a balance that can be changed// by deposits and withdrawals

private double balance;

/* * Constructs a bank account with a zero balance */

public BankAccount(){

balance = 0;}/* * Deposits money into the bank account. @param amount * the amount to deposit */public synchronized void deposit(double amount){

Page 2: Bank Account Sync

System.out.println("Depositing " + amount);balance = balance + amount;System.out.println("new balance is " + balance);notifyAll();

}/* * Withdraws money from the bank account. @param amount the

amount to * withdraw */public synchronized void withdraw(double amount){

try{while ( balance < amount ){

System.out.println("Withdraw " + amount + " was blocked");

wait();}System.out.println("Withdrawing " + amount);balance = balance - amount;System.out.println("new balance is " + balance);}catch ( Exception e){

System.out.println("Exception Caught");}

}

/* * Gets the current balance of the bank account. @return the

current balance */

public double getBalance(){

return balance;}

}

package BankAccountTesterTrial2;

public class DepositAgent extends Thread {/* * A BankAccount is created and the deposit * function is run to try and deposit the * amount specified */

Page 3: Bank Account Sync

BankAccount caccount;

int amount = 0;

public DepositAgent( BankAccount account, int funds){

/* * Constructor for DepositAgent * @param BankAccount, funds(amount to deposit) */caccount = account;amount = funds;

}

public void run(){

/* * Runs the thread */

caccount.deposit(amount);}

}

package BankAccountTesterTrial2;

public class WithdrawAgent extends Thread {/* * Creates a BankAccount and runs the * WithdrawAgent to try and withdraw the amount * of funds specified * */

BankAccount caccount;int amount = 0;

public WithdrawAgent (BankAccount account, int funds){

/* * Constructor for the WithdrawAgent * @param account, funds */caccount = account;amount = funds;

}public void run (){

/* * Runs the thread */caccount.withdraw(amount);

}}

Page 4: Bank Account Sync