避免死锁示例
2022-09-02 00:19:30
我想知道在下面的示例中避免死锁的替代方法是什么。以下示例是典型的银行帐户转帐死锁问题。在实践中解决它的更好方法是什么?
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);
}