Java Reference
In-Depth Information
I didn't name the program SomethingsWrong without a reason, though. I
claim that this program worked because of sheer luck. The two BankTeller
threads have a reference to the same BankAccount object. In other words, these
two threads share the same memory. The threads ran quickly enough that they
did not ever block in the middle of running. However, if they had blocked for
any reason, a different result might have occurred. To test out my theory, I
added a call to sleep() in both the deposit() and withdraw() methods of
BankAccount, forcing the BankTeller threads to become blocked in the middle
of a transaction:
public void deposit(double amount)
{
double prevBalance = balance;
try
{
Thread.sleep(4000);
}catch(InterruptedException e)
{}
balance = prevBalance + amount;
}
public void withdraw(double amount)
{
double prevBalance = balance;
try
{
Thread.sleep(4000);
}catch(InterruptedException e)
{}
balance = prevBalance - amount;
}
Adding the calls to sleep() forces the threads to take turns executing. Run-
ning the SomethingsWrong program again generates a different result, as
shown in Figure 15.9. Notice that after two $100 deposits, followed by a $200
withdrawal, the balance should be $1000, but for some reason is only $800.
Figure 15.9 The SomethingsWrong program demonstrates a problem with our
BankAccount class.
Search WWH ::




Custom Search