为什么在我的代码中有一个竞争条件,当所有帐户同步?怎么会有竞争条件?
class Transfer implements Runnable {
Konto fromAccount;
Konto toAccount;
Integer amount;
public void run() {
synchronized (fromAccount) {
if (fromAccount.book(-amount)) {
toAccount.book(amount);
}
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException
Account thomas = new Account(1234, 100);
Account mathias = new Account(5678, 100);
Thread transfer1 = new Thread(new Transfer(80, thomas, mathias));
Thread transfer2 = new Thread(new Transfer(95, mathias, thomas));
transfer1.start();
transfer2.start();
transfer1.join();
transfer2.join();
}
从我的理解,transfer1锁定其fromAccount(托马斯)和transfer2锁定其fromAccount(马蒂亚斯),所以不应该他们都在僵局结束了?
是否有死锁或竞态条件?你提到了两者,但它们是不同的。看起来像你有一个潜在的种族,但没有一个快速浏览僵局。 – Brick