gpt4 book ai didi

java - 从 run 方法调用同步方法

转载 作者:行者123 更新时间:2023-11-30 06:20:58 26 4
gpt4 key购买 nike

我有一个 Account 模型,我想同步提取它。但是即使在使方法同步并从 run 方法调用它之后,输出顺序仍然存在一些问题。这是我的代码。我真的不知道是什么问题。

public class Account {
private double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}


public class WithdrawThread implements Runnable {
private double amount;
private Account account;

public WithdrawThread(Account account, double amount) {
this.account = account;
this.amount = amount;
}

public synchronized void withdraw(double amount) {

double bal = account.getBalance();
if (amount > account.getBalance())
throw new IllegalArgumentException("wrong amount");
bal -= amount;
account.setBalance(bal);
System.out.println(amount + " withdraw in thread number" + Thread.currentThread().getId() + " balance is " + bal);
}

public void run() {
withdraw(amount);
}

public class MainThread {
public static void main(String[] args) {
Account account = new Account(200);
new Thread(new WithdrawThread(account, 40)).start();
new Thread(new WithdrawThread(account, 10)).start();
new Thread(new WithdrawThread(account, 10)).start();
new Thread(new WithdrawThread(account, 20)).start();
new Thread(new WithdrawThread(account, 30)).start();
new Thread(new WithdrawThread(account, 10)).start();
new Thread(new WithdrawThread(account, 40)).start();
}
}

sample output

最佳答案

如 Sotirios Delimanolis 所述,同步方法使用来自调用它的对象的锁,该对象是 WithdrawThread 实例。你想锁定帐户...

要么使提取帐户方法,要么使用同步块(synchronized block)。

public void withdraw(double amount) {
double bal;
synchronized(account) {
bal = account.getBalance();
if (amount > account.getBalance())
throw new IllegalArgumentException("wrong amount");
bal -= amount;
account.setBalance(bal);
}
System.out.println(amount + " withdraw in thread number" + Thread.currentThread().getId() + " balance is " + bal);
}

关于java - 从 run 方法调用同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com