让我们假设我有下面这些类:
public class Service {
public void transferMoney(Account fromAcct, Account toAcct, int amount) {
synchronized (fromAcct) {
synchronized (toAccount) { // could we use here only one synchronized block?
fromAcct.credit(amount);
toAccount.debit(amount);
}
}
}
}
class Account {
private int amount = 0;
public void credit(int sum) {
amount = amount + sum;
}
public void debit(int sum) {
amount = amount - sum;
}
}
例如,我知道我们只能在
transferMoney
方法中更改fromAcct
和toAcct
对象的状态。因此,我们能否使用一个synchronized块重写我们的方法?public class Service {
private final Object mux = new Object();
public void transferMoney(Account fromAcct, Account toAcct, int amount) {
synchronized(mux) {
fromAcct.credit(amount);
toAcct.debit(amount);
}
}
}