首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JMH多线程中使用AtomicInteger?

在JMH多线程中使用AtomicInteger?
EN

Stack Overflow用户
提问于 2016-09-26 20:45:46
回答 1查看 333关注 0票数 1

我正在使用JMH来测试我的项目的一些功能。当我尝试在AtomicInteger中使用它的@GroupThreads时,我无法重置AtomicInteger,它只是随着时间的推移而增加。我还尝试用if else检查并重置AtomicInteger,但失败了。你能给我一些解决问题的建议吗?非常感谢。

代码语言:javascript
复制
class JMHSample_15_Asymmetric {

  private var counter: AtomicInteger = _

  @Setup
  def up() {
    counter = new AtomicInteger
  }

  @Benchmark
  @Group("g")
  @GroupThreads(3)
  def inc: Int = {
    counter.compareAndSet(10,-1)
    counter.incrementAndGet
  }
  @Benchmark
  @Group("g")
  @GroupThreads(1)
  def get: Int = {
    println("Counter --> "+ counter.get)
    counter.get
  }

}
EN

回答 1

Stack Overflow用户

发布于 2016-09-27 18:13:39

这是一种内在的竞赛。您可能永远不会在CAS(10, -1)中观察到10 --当多个线程在10上递增运行时--因此会错过重置操作。如果你想正确地同步计数器模N,我建议详细说明这个未经测试的草图:

代码语言:javascript
复制
int countUp() {
  int cur, next;
  do {
    cur = counter.get();
    next = cur < N ? (cur + 1) : 0;
  } while (!counter.compareAndSet(cur, next));
  return next;
}

...or,在Java8中:

代码语言:javascript
复制
int countUp() {
  return counter.updateAndGet(v -> (v < N) ? (v + 1) : 0);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39703237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档