我最近遇到这个问题来到这里,我想找到低于目前的代码僵局。我有与Java多线程或没有经验,这就是为什么我在这里,以更好地理解这个问题。
public class BankAccount {
private final int customerId;
private int balance;
public BankAccount(int customerId, int openingBalance) {
this.customerId = customerId;
this.balance = openingBalance;
}
public void withdraw(int amount) throws OverdrawnException {
if (amount > balance) {
throw new OverdrawnException();
}
balance -= amount;
}
public void deposit(int amount) {
balance += amount;
}
public int getCustomerId() {
return customerId;
}
public int getBalance() {
return balance;
}
}
class TransferOperation extends Thread {
int threadNum;
TransferOperation(int threadNum) {
this.threadNum = threadNum;
}
private void transfer(BankAccount fromAccount, BankAccount toAccount, int transferAmount) throws OverdrawnException {
synchronized (fromAccount) {
synchronized (toAccount) {
fromAccount.withdraw(transferAmount);
toAccount.deposit(transferAmount);
}
}
}
// ...
}
我有这样的上面一段代码。我想找个地方死锁可能出现在上面的代码。我觉得只有把它可能发生在两个同步块。我对吗?
如果是,有人可以帮助我了解为什么?我可以猜测,很可能是因为退出,存款保持一个线程等待另一个。但是,这是一个总的猜测,这就是为什么寻求帮助这里。
另外,如果我想阻止僵局,我怎么会去它的代码?
任何帮助表示赞赏。