java volatile 理解,深入理解Java中的volatile

本文探讨了Java中volatile关键字的作用,特别是它如何确保内存可见性。在给出的代码示例中,解释了为何在特定情况下无法得到1,0的输出,并分析了Java内存模型(JMM)的happens-before关系。讨论了线程并发执行时可能出现的不同输出情况以及 volatile 写操作的内存顺序效应。
摘要由CSDN通过智能技术生成

Does Java allows output 1, 0? I've tested it very intensively and I cannot get that output. I get only 1, 1 or 0, 0 or 0, 1.

public class Main {

private int x;

private volatile int g;

// Executed by thread #1

public void actor1(){

x = 1;

g = 1;

}

// Executed by thread #2

public void actor2(){

put_on_screen_without_sync(g);

put_on_screen_without_sync(x);

}

}

Why?

On my eye it is possible to get 1, 0. My reasoning.

g is volatile so it causes that memory order will be ensured. So, it looks like:

actor1:

(1) store(x, 1)

(2) store(g, 1)

(3) memory_barrier // on x86

and, I see the following situation:

reorder store(g, 1) before store(x,1) (memory_barrier is after (2)).

Now, run thread #2. So, g = 1, x = 0. Now, we have expected output.

What is incorrect in my reasoning?

解决方案

Any actions before a volatile write happen before (HB) any subsequent volatile read of the same variable. In your case, the write to x happens before the write to g (due to program order).

So there are only three possibilities:

actor2 runs first and x and g are 0 - output is 0,0

actor1 runs first and x and g are 1 because of the happens before relationship HB - output is 1,1

the methods run concurrently and only x=1 is executed (not g=1) and the output could be either 0,1 or 0,0 (no volatile write so no guarantee)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值