AtomicInteger用于有限序列生成

sat*_*ish 7 java atomic

我们如何使用AtomicInteger进行有限的序列生成,假设序列号必须在1到60之间.一旦序列达到60,它必须从1开始.我写了这段代码虽然不太确定这是否是线程安全的?

public int getNextValue()
{
 int v;
 do
 {
   v = val.get();
   if ( v == 60)
   {
    val.set(1);
   }
 }
  while (!val.compareAndSet(v , v + 1));
   return v + 1;
  }
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 15

你可以做到

return val.getAndIncrement() % 60;
Run Code Online (Sandbox Code Playgroud)

除非你担心超过整数最大值(2147483647).如果这是一个问题,你可以看看getAndIncrement实现:

public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}
Run Code Online (Sandbox Code Playgroud)

所有你需要改变的是int next...:

int next = (current + 1) % 60;
Run Code Online (Sandbox Code Playgroud)

哎呀.这循环通过0-> 59.您需要1-> 60,因此在返回值中添加一个以获得所需的结果.


小智 6

您可以使用Java 8在一行中完成此操作。

AtomicInteger counter = new AtomicInteger();

public int getNextValue() {
    return counter.updateAndGet(n -> (n >= 60) ? 1 : n + 1);
}
Run Code Online (Sandbox Code Playgroud)