# Java中小于号执行顺序

{% embed url="<https://v.douyin.com/rREs7sQ/>" %}

{% embed url="<https://www.bilibili.com/video/BV1na411J7nh/>" %}

昨天刷到军哥这个视频太神奇了

大概意思就说两个线程

第一个线程不断的对 a b 进行加加

然后第二个线程呢

去找 a 小于 b 的那么一个时刻

但神奇就在于

因为我们加加的时候是先对 a 加加

再对 b 加加

所以按说不会有那么一个时刻

a 会小于 b

但我们跑一下代码看一下

打开会有这么多 a 小 a b 的时候

大概意思就是说啊两个县城

那为什么会这样呢后来我发现啊

原因是在执行这个表达式的时候

（因为是从左到右执行嘛）

所以他在拿到 a 值和 b 值中间

会有一个很短的时间差

那在这一个很短的时间内呢

a b 的值都已经发生变化了

所以就意味着我们是在拿

几毫秒之前的 a

和几毫秒以后的 b

去做比较

举个例子

假如我们在获取 a 的值的时候

a b 都是然后呢

过几毫秒我们去获取 b 值的时候

这时候 ab 都变成200了

但是呢我们只拿到了 b 的值（200）

也就是说我们拿100跟200比

就会出现这种情况

那怎么避免这种情况呢

我们就要想办法

在这拿到一个 ab 的快照

我们int

a s 等于 a

然后呢 b s 等于 b

我们要想办法

在获取这个 a s 和 bs 值的时候

这个加加先停一下

比如说执行到这的时候告诉哎你先停

你先别加

我先获取一个快照

然后你再加

所以呢

我们要给这两段代码上一把同样的锁

好

然后下边比较的时候呢

我们用 a s 和 b s

但这个作用域有点问题

我们拿到外边来

a s b s

ok 然后呢我们比较用 as bs

我们再来运行一下

大家看！没有任何问题了


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunzsh.gitbook.io/xiaoshan.bug/java-zhong-xiao-yu-hao-zhi-xing-shun-xu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
