Examine the program in the files Account.java and ATM.java (given below: cut and paste into your editor). Try running the program. What is wrong with it? What, in principle, needs to be done to fix it?
public class Account
{
static int balance = 10000;
static final int NTHREADS = 10;
public static void main (String [] args)
{
ATM [] cashMachines = new ATM [NTHREADS];
for (int i = 0; i < NTHREADS; i++)
{
cashMachines [i] = new ATM ();
cashMachines [i].start ();
}
try
{
for (int i = 0; i < NTHREADS; i++)
{
cashMachines [i].join (); // Wait for the thread to complete
}
}
catch (InterruptedException ex) { }
System.out.println ("Balance is " + balance);
if (balance < 0)
{
System.out.println ("You are somewhat overdrawn");
}
} // main
} // Account
public class ATM extends Thread
{
private void withdraw (int amount)
{
if (Account.balance >= amount)
{
// Wait, to simulate some calculation
try { sleep (100); }
catch (InterruptedException e) { }
Account.balance -= amount;
}
// else would go overdrawn: do not withdraw any more
} // withdraw
@Override
public void run ()
{
withdraw (5000);
} // run
} // ATM
NB: You may need to replace some HTML characters in the cut and pasted text for the 2 classes: < should be <, > should be >, " should be ".