You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未使用volatile的Java程序中,r1==0且r2==0是否可能出现?

问题

我是否理解正确:即使a和b未声明为volatile,并行执行run1()和run2()时,r10且r20的结果在任何情况下都不可能出现?

示例代码

public class Example {

    private int a = 0;
    private int b = 0;

    public void run1() {
        b = 1; // (1)
        int r2 = a; // (2)
    }

    public void run2() {
        a = 2; // (3)
        int r1 = b; // (4)
    }
}

我的分析与结论

我的结论基于《Java Memory Model》第17.4.5节的表述:

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y)

具体分析:

  • (1)和(2)是同一线程的操作,程序顺序上(1)先于(2),因此(1) happens-before (2)。
  • 同理,(3) happens-before (4)。

该程序仅包含4个操作,存在4!种可能的执行顺序。经逐一分析,任何导致r10且r20的执行都会违反上述happens-before关系,因此是非法的。


内容的提问来源于stack exchange,提问作者yaskovdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:39:55