gpt4 book ai didi

java - volatile 关键字原子性

转载 作者:行者123 更新时间:2023-12-03 03:49:52 25 4
gpt4 key购买 nike

我正在努力学习volatile field modifier在多线程中。我看到这样的说法:

Volatile is preferred in cases when one thread reads and writes a shared variable and other threads just read the same. Whereas if there are more than 2 threads performing read and write both on the shared variable then only volatile is not enough, you need to have synchronization as well.

我知道 volatile 提供了可见性和发生前保证,但是是否可以给出一个简单的小代码示例来演示上述语句,其中需要同步块(synchronized block)?

最佳答案

public class TwoInts {
private volatile int i1;
private volatile int i2;

public void set(int i1, int i2) {
this.i1 = i1;
this.i2 = i2;
}

public boolean same() {
return i1 == i2;
}
}

现在,如果您有一个线程执行此操作:

while (true) {
twoInts.set(i, i);
i++;
}

第二个线程执行此操作:

while (true) {
if (!twoInts.same()) {
System.out.println("Ooops!!");
}
}

然后你就会观察到引用文本所讨论的问题。如果您重写 TwoInts 类以使方法同步,那么“Oooops!!”消息将停止。

关于java - volatile 关键字原子性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472032/

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