//简单顺序死锁
public class LeftRightDeadlock{
private final Object left = new Object();
private final Object right = newe Object();
public void leftRight(){
synchronized(left){
synchronized(right){
doSomething();
}
}
}
public void rightLeft(){
synchronized(right){
synchronized(left){
doSomethingElse();
}
}
}
}
//动态的顺序死锁
public void transferMoney(Account fromAccount,Account toAccount,DollarAmount amount)
throws InsufficientFundsException{
synchronized(fromAccount){
synchronized(toAccount){
if(fromAccount.getBalance().compareTo(amount) < 0){
throw new InsufficientFundsException();
}else{
fromAccount.debit(amount);
toAccount.credit(amount);
}
}
}
}
所有线程似乎是按照相同的顺序来获得锁,但是实际上,获得锁的顺序取决于外部的输入,如果两个线程同时调用transferMoney(),其中一个线程从X向Y转账,另外一个线程
从Y向X转账,就会发生死锁