java volatile i_Java parallel volatile i++

I have a global variable

volatile i = 0;

and two threads. Each does the following:

i++;

System.out.print(i);

I receive the following combinations. 12, 21 and 22.

I understand why I don't get 11 (volatile disallows the caching of i) and I also understand 12 and 22.

What I don't understand is how it is possible to get 21?

The only possible way how you can get this combination is that the thread that prints later had to be the first to increment i from 0 to 1 and then cached i==1. Then the other thread incremented i from 1 to 2 and then printed 2. Then the first thread prints the cached i==1. But I thought that volatile disallow caching.

Edit: After running the code 10,000 times I got 11 once. Adding volatile to i does not change the possible combinations at all.

markspace is right: volatile forbids caching i but i++ is not atomic. This means that i still gets sort of "cached" in a register during the incrementation.

r1 = i

//if i changes here r1 does not change

r1 = r1 + 1

i = r1

This is the reason why 11 is still possible. 21 is caused because PrintStreams are not synchronized (see Karol Dowbecki's answer)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值