Java Reference
In-Depth Information
Again, the BankTeller class seems simple enough. To test out the BankTeller
and BankAccount classes, I wrote the following program named Some-
thingsWrong that creates a single BankAccount object and two BankTeller
threads. Study the program and try to determine the output, which is shown
in Figure 15.8.
public class SomethingsWrong
{
public static void main(String [] args)
{
BankAccount account = new BankAccount(101, 1000.00);
System.out.println(“Initial balance: $”
+ account.getBalance());
Thread teller1 = new BankTeller(account);
Thread teller2 = new BankTeller(account);
teller1.start();
teller2.start();
Thread.yield();
System.out.println(“Withdrawing $200...”);
account.withdraw(200);
System.out.println(“\nFinal balance: $”
+ account.getBalance());
}
}
I added the call to yield() so that the main() thread would give the two
BankTeller threads a chance to execute first, thereby increasing the
likelihood that the two deposits occur before the withdrawal. This does
not guarantee that the deposits will occur first, and the final balance is
still $1000.00 with or without the call to yield() in main().
The output of the SomethingsWrong program seems to be consistent with
the logic of the program: The initial balance is $1000, two deposits of $100 are
made and a withdrawal of $200 is made, so the final balance should be $1000,
which it is.
Figure 15.8
The SomethingsWrong program appears to be working fine.
Search WWH ::




Custom Search