【问题标题】:Using AtomicInteger safely to check first首先安全地使用 AtomicInteger 进行检查
【发布时间】:2012-04-14 01:58:09
【问题描述】:

如何在 AtomicInteger 变量中执行“check-then-act”?
IE。根据结果​​检查此类变量 first 和 inc/dec 的值的最安全/最佳方法是什么?
例如。 (高级)
if(count < VALUE) count++; //原子地使用AtomicInteger

【问题讨论】:

标签: java multithreading concurrency atomic


【解决方案1】:

您需要编写一个循环。假设 count 是您的 AtomicInteger 引用,您可以编写如下内容:

while(true)
{
    final int oldCount = count.get();
    if(oldCount >= VALUE)
        break;
    if(count.compareAndSet(oldCount, oldCount + 1))
        break;
}

以上将循环,直到:(1)您的if(count < VALUE) 条件不满足;或 (2) count 成功递增。使用compareAndSet 执行递增让我们保证在设置新值时count 的值仍为oldCount(因此仍小于VALUE)。

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 8,则可以这样解决。它是线程安全的,并且是原子执行的。

    AtomicInteger counter = new AtomicInteger();
    static final int COUNT = 10;
    
    public int incrementUntilLimitReached() {
        return counter.getAndUpdate((n -> (n < COUNT) ? n + 1 : n));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2022-01-19
      • 2019-08-22
      • 2016-02-22
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多