gpt4 book ai didi

Java 同步未按(我)预期工作

转载 作者:行者123 更新时间:2023-12-02 08:27:03 24 4
gpt4 key购买 nike

程序员 friend 们。我正在使用非常简单的代码(或者至少看起来很简单)来测试 Java 线程功能。我有此类帐户:

public class Account {
protected double balance;

public synchronized void withdraw(double value) {
this.balance = this.balance - value;
}

public synchronized void deposit(double value) {
this.balance = this.balance + value;
}

public synchronized double getBalance() {
return this.balance;
}
}

我有两个线程:Depositer,存款 10 美元一千次:

public class Depositer extends Thread {
protected Account account;

public Depositer(Account a) {
account = a;
}

@Override
public void run() {
for(int i = 0; i < 1000; i++) {
this.account.deposit(10);
}
}
}

还有 Withdrawer,提取 10 美元一千次:

public class Withdrawer extends Thread {
protected Account account;

public Withdrawer(Account a) {
account = a;
}

@Override
public void run() {
for(int i = 0; i < 1000; i++) {
this.account.withdraw(10);
}
}
}

此安排执行者:

public class Main {
public static void main(String[] args) {
Account account = new Account();
Thread c1 = new Depositer(account);
Thread c2 = new Withdrawer(account);

c2.start();
c1.start();

System.out.println(account.getBalance());
}
}

由于方法是同步的,我只是期望最后余额始终为0,但有时不会发生这种情况。我真的不明白为什么。有人能看出我的错在哪里吗?

最佳答案

c2.start()c1.start() 异步运行该进程。您的主线程需要等待这两个线程完成才能打印结果。

调用

try {
c2.join();
c1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

在调用 println 之前。

参见join .

Waits for this thread to die.

关于Java 同步未按(我)预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1020751/

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