我想知道在下面的示例中避免死鎖的替代方法是什麼。以下示例是一個典型的銀行帳戶傳輸死鎖問題。在實踐中解決它有哪些更好的方法?避免死鎖示例
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);
}
你的例子不是經典的死鎖例子。它總是鎖定同一個線程的帳戶,所以不會發生死鎖。是否在傳輸方法中嘗試使用此代碼:靜態無效傳輸(BankAccount from,BankAccount to,double amount){ synchronized(from){ \t from.withdraw(amount); synchronized(to){ to.deposit(amount); } } } – supernova