gpt4 book ai didi

java - 并发:使用非同步方法更改变量

转载 作者:行者123 更新时间:2023-12-01 21:12:51 27 4
gpt4 key购买 nike

以此ConcurrentDouble类定义为例:

public class ConcurrentDouble {

public double num = 0;

public void subtract(double num) {
this.num -= num;
}

public void add(double num) {
this.num += num;
}
}

现在,如果我执行以下操作,

public class Test {
public static void main(String[] args) {
ConcurrentDouble d1 = new ConcurrentDouble();

Thread one = new Thread(() -> { d1.add(5); }).start();
Thread two = new Thread(() -> { d1.subtract(5); }).start();

one.join();
two.join();

System.out.println(d1.num); // <-- OUTPUT
}
}

我们知道数字从 0 开始,并且我们希望它以 0 结尾。该数字有可能变成 -5.05.0 吗?

最佳答案

是的,这是可能的。 -=+= 不是原子操作。即使这样,JVM 也不保证对 double 的写入是原子的。

关于java - 并发:使用非同步方法更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40833463/

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