我想知道在以下例子中避免死锁的替代方法是什么。下面的例子是一个典型的银行账户转账死锁问题。在实践中解决它的更好方法有哪些?
class Account {
double balance;
int id;
public Account(int id, double balance){
this.balance = balance;
this.id = id;
}
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
}
class Main{
public static void main(String [] args){
final Account a = new Account(1,1000);
final Account b = new Account(2,300);
Thread a = new Thread(){
public void run(){
transfer(a,b,200);
}
};
Thread b = new Thread(){
public void run(){
transfer(b,a,300);
}
};
a.start();
b.start();
}
public static void transfer(Account from, Account to, double amount){
synchronized(from){
synchronized(to){
from.withdraw(amount);
to.deposit(amount);
}
}
}
}
我想知道,如果我按照以下方式将传输方法中的嵌套锁定分开,死锁问题是否会得到解决。
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}