Java Reference
In-Depth Information
{
System.out.println(“Transferring from “
+ source.getNumber() + “ to “ + dest.getNumber());
synchronized(source)
{
Thread.yield();
synchronized(dest)
{
System.out.println(“Withdrawing from “
+ source.getNumber());
source.withdraw(amount);
System.out.println(“Depositing into “
+ dest.getNumber());
dest.deposit(amount);
}
}
}
}
It wasn't hard to create deadlock with this class, especially because I had the
LazyTeller thread yield after obtaining its first of two locks. The following
DeadlockDemo program creates two bank accounts, checking and savings.
Then, two LazyTeller objects transfer money between them. Notice that teller1
transfers $250 from checking to savings, whereas teller2 transfers $250 from
savings to checking. Figure 15.11 shows the output of the DeadlockDemo pro-
gram. Study the output to try to determine how far the program ran before it
locked up.
public class DeadlockDemo
{
public static void main(String [] args)
{
System.out.println(“Creating two bank accounts...”);
ThreadSafeBankAccount checking =
new ThreadSafeBankAccount(101, 1000.00);
ThreadSafeBankAccount savings =
new ThreadSafeBankAccount(102, 5000.00);
System.out.println(“Creating two teller threads...”);
Thread teller1 = new LazyTeller(checking, savings);
Thread teller2 = new LazyTeller(savings, checking);
System.out.println(“Starting both threads...”);
teller1.start();
teller2.start();
}
}
Search WWH ::




Custom Search