避免死锁示例 [英] Avoid Deadlock example
本文介绍了避免死锁示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道在以下示例中有哪些替代方法可以避免死锁。以下示例是传输死锁问题的典型银行帐户。在实践中有哪些更好的解决方法?
I am wondering what are the alternative ways to avoid deadlock in the following example. The following example is a typical bank account transferring deadlock problem. What are some better approaches to solve it in practice ?
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);
}
}
}
}
I我想知道它是否会解决死锁问题如果我在我的传输方法中将嵌套锁分开,如下所示
I am wondering will it solve the deadlock issue if I separate the nested lock out in my transfer method like the following
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}
推荐答案
对帐户进行排序。死锁来自账户的排序(a,b vs b,a)。
Sort the accounts. The dead lock is from the ordering of the accounts (a,b vs b,a).
所以尝试:
public static void transfer(Account from, Account to, double amount){
Account first = from;
Account second = to;
if (first.compareTo(second) < 0) {
// Swap them
first = to;
second = from;
}
synchronized(first){
synchronized(second){
from.withdraw(amount);
to.deposit(amount);
}
}
}
这篇关于避免死锁示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文