我很抱歉这个基本的问题,但是我很好奇为什么我没有得到下面代码的正确结果。我有一个基本的Account类,它有3个非同步和3个同步的方法,做同样的工作。我期望当我使用synchronized关键字时计算出正确的结果,但是当我运行应用程序时,不幸的是我得到了一个错误的错误。我在这里错过了什么?提前感谢各位!
这是Account
类
public class Account {
private double balance;
public Account(int balance) {
this.balance = balance;
}
public boolean rawWithDraw(int amount) {
if (balance >= balance) {
balance = balance - amount;
return true;
}
return false;
}
public void rawDeposit(int amount) {
balance = balance + amount;
}
public double getRawBalance() {
return balance;
}
public boolean safeWithDraw(final int amount) {
synchronized (this){
if (balance >= amount) {
balance = balance - amount;
return true;
}
}
return false;
}
public void safeDeposit(final int amount) {
synchronized (this) {
balance = balance + amount;
}
}
public double getSafeBalance() {
synchronized (this) {
return balance;
}
}
}
这是主要的应用程序
public class Main {
public static void main(String[] args) {
Account account1 = new Account(0);
Thread tA = new Thread(() -> account1.safeDeposit(70));
Thread tB = new Thread(() -> account1.safeDeposit(50));
tA.setName("thread-A");
tB.setName("thread-B");
tA.start();
tB.start();
System.out.println("The balance is : " + account1.getRawBalance());
}
}
当我运行代码的时候,有时候会打印70
,有时候会打印0
,有时候会打印120
。是什么原因导致的呢?
1条答案
按热度按时间mlmc2os51#
您没有将
getRawBalance()
作为synchronized方法包括在内,因此允许它与两个synchronized方法中的任何一个并发运行。因此,您可以在任一方法执行之前、两个方法都执行之后或在一个方法与另一个方法之间查看结果,给出四种不同的可能结果。