gpt4 book ai didi

java - volatile 引用并随后设置变量的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:18 27 4
gpt4 key购买 nike

考虑片段:

class Mutable {
private volatile int value;
public int get()
{
return value;
}
public int set(int value)
{
this.value = value;
}
}

class Test {
public volatile Mutable m;
}

所以使用下面的顺序:

Thread-1: get()     // returns 2
Thread-2: set(3)
Thread-1: get() // guaranteed to return 3 due to volatile with property value

但我无法理解作者的以下注释-

one note however, when m is assigned, the internal value will be correctly visible. it is only after subsequent calls to set() which do not write m that you have problems.

请举例说明。他说的是哪个问题?

最佳答案

最后一条评论之所以令人困惑,是因为它被断章取义了。您提供的示例代码与 original code 中的不同该评论所针对的。在原始 代码中, 不是 易变的。当 value 不可变时,就会出现以下情况。

线程 1:

Mutable tmp = new Mutable();
tmp.set(3);
Test.m = tmp;

线程 2:

Test.m.get();  // *** this is guaranteed to return 3 due to the happens before rules.

线程 1:

Test.m.set(5);

线程 2:

Test.m.get();  // no guaranatees here, could be 3, could be 5

我的评论指的是“***”部分,其中 m 的可变赋值提供了发生在关系之前的关系,这使得“3”对 Thread2 可见(由于m)。 (重申一下,value 在此示例中不是易变的)。

关于java - volatile 引用并随后设置变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39073702/

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