在 volatile 变量存在的情况下会发生重新排序吗? [英] Can a reordering happen in the presence of a volatile variable?

查看:33
本文介绍了在 volatile 变量存在的情况下会发生重新排序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的做法如下,我的程序中只有 2 个线程.

I am doing as follows, there's only 2 threads in my program.

// Thread 1
write a = 0
write a = 1
write volatile b = 1

// Thread 2
read volatile b // this I always do after write volatile b in the 1st thread
read a

我读过 Java 内存模型,根据我在线程 2 中的理解 read a 总是给我 1.

I've read on Java Memory Model and from what I understand in thread 2 read a will ALWAYS give me 1.

我想知道我的理解是否正确.

I would like to know if this my understanding is correct or not.

特别是重新排序是否仍然发生,所以我在第二个线程中看到 a = 0?

In particular CAN A REORDERING still HAPPEN so I see a = 0 in the 2nd thread?

推荐答案

您的假设基本正确.但是,我会稍微重申一下以符合 JMM 的保证.

Your assumptions are mostly correct. However, i would restate it slightly to match what the JMM guarantees.

如果线程 2 读取 b 并看到值 1,那么后续读取的 a 将为 1.就像你说的,如果线程2 总是在线程 1 完成写入后在"读取 b,然后线程 2 将看到值 1,并且读取 a 将如您所料.

If Thread 2 reads b and sees value 1, then the subsequent read of a will be 1. Like you said, if Thread 2 always reads b "after" Thread 1 finishes writing it, then Thread 2 will see the value 1 and the read of a will be as you expect.

这篇关于在 volatile 变量存在的情况下会发生重新排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆