gpt4 book ai didi

java - Compare 在 AtomicInteger.incrementAndGet() 的 CompareAndSwap 中比较什么?

转载 作者:行者123 更新时间:2023-11-30 05:59:02 24 4
gpt4 key购买 nike

我知道CompareAndSwap是在java并发中的AtomicInteger.incrementAndGet()等方法的底层使用的,它的工作原理就像无限循环,直到成功并阻塞它的线程

It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it).

那么incrementAndGet()中的给定值内存位置的内容是什么?

最佳答案

当一个线程看到当前值(例如 1)时,会将其递增到 2 作为给定值,并比较 2 为当前时刻内存中的实际值。

如果成功,将返回2

否则,它将检索最新值,假设为 x,并递增到 x + 1 作为给定值。

...

此过程将持续到比较成功为止。

关于java - Compare 在 AtomicInteger.incrementAndGet() 的 CompareAndSwap 中比较什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52590074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com