/*
Code example based on author's work found on
http://www.hh.se/ide/utbildning/Kursplaner/02-03/oop/exercises/exercise6.html
Shows how threads can be synchronized to avoid conflict
*/
//Implements Runnable is required for a multithreaded class
class ATM implements Runnable{
//Private variable that represents an instance of BankAccount Object
private BankAccount theAccount;
private String location;
//Here is the constructor for the ATM instance, accept a BankAccount
//object called a. To start the ATM it must have an account
public ATM(BankAccount a, String l){
theAccount = a;
location = l;
}
//What runs the threads (or instances of BankAccount)
//and produces the output
public void run(){
boolean overDraw;
long balance;
int acctnum;
//Initialize overdraw to false, because we don't know the
//the account balance when the ATM thread first starts.
overDraw = false;
//The while loop will continue until account is overdrawn
while(!overDraw){
//when using a thread the try/catch is reqired to check
//thread status
try{
Thread.sleep(9000);
}catch(InterruptedException e){
System.out.print("thread error"); }
//Java statements that process within the thread
overDraw = theAccount.withdraw(100000);
acctnum = theAccount.getacct();
balance = theAccount.getbalance();
System.out.print("------------- \n");
System.out.print("The Account: " + acctnum + " The Balance; " +
balance + " " + location + "\n");
}//end while
}
//***** Here is the main method, it is where ATM starts ******
//Unique threads (2 ATMS) are created here.
public static void main(String[] args){
//Construct 2 accounts
int acctnum1 = 123;
int acctnum2 = 234;
BankAccount BankofNM = new BankAccount(9000000, acctnum1);
BankAccount BankofNY = new BankAccount(1000000, acctnum2);
//Assign account to ATM,
//************* Create Instances of ATM ***************
//Acount 123 is being accessed from two locations,
//university and city
ATM university = new ATM(BankofNM, "university");
ATM city = new ATM(BankofNM, "city");
//Acount 234 is being accessed from one locations,
//the mall
ATM mall = new ATM(BankofNY, "mall");
//************ Run Instances of ATM ****************
//Each ATM will be unique thread, to synchronize
//activity on the account.
//Because ATM class implements runnable it can be used as a thread
new Thread(university).start();
new Thread(city).start();
new Thread(mall).start();
}
}