java中的变量是原子的,Java中变量读写的原子性

this is a followup on another question of mine.

@templatetypedef answered the question (appreciated), and in his answer he wrote:

As a note - atomicity does not mean "all other threads will be blocked

until the value is ready. It means all other threads will either see

the state purely before the operation is done or purely after the

operation is done, but nothing else.

I have a confusion regarding this, and here’s why:

It says here:

Atomic actions cannot be interleaved, so they can be used without fear

of thread interference.

What I infer from this, is that it contradicts what he wrote.

If we have 2 int variables i1 and i2, and we do the atomic operation i1=i2; and this operation is executed by threadX.

Then if atomic actions cannot be interleaved as indicated above, it means that during this atomic operation (executed by threadX), no other threadY is allowed to access (for either read or write) that same variable i2, hence, no other threadY, is allowed to access that same variable during the atomic operation, so some form of blocking does exist.

Did I get this right?

Thanks...

解决方案

To the best of my knowledge there is no atomic i1 = i2 operation. You can atomically read an int and you can atomically write to one, but you can't do both in the same operation with synchronization. So i1 = i2 is two different atomic operations, a read followed by a write. You are guaranteed that nothing will interleave the read operation so you won't see partial updates to i2 when you read it, and you are guaranteed that nothing will interleave the write to i1, but there's no guarantee that nothing will happen in between those two atomic operations.

Lets say Thread t1 is going to do:

i2 = 10

i1 = i2

And thread t2 is going to do:

i1 = 7

i2 = 18

System.out.println(i1)

What you are guaranteed is that t1 will end up assigning either 10 or 18 to i1 but you can't know which. However, you are guaranteed it can't be any other value because the read of i2 and the write to i1 are atomic so you can't end up seeing some of the bits of i2 while it's being modified. Similarly, t2 is guaranteed to print either 10, 18, or 7 and it can't print anything else. However, without synchronization there's no way to know which of those 3 values it will end up printing.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值