线程安全的轮询算法
public class AtomicIntegerRoundRobin {
private final int totalIndexes;
private final AtomicInteger atomicInteger = new AtomicInteger(-1);
public AtomicIntegerRoundRobin(int totalIndexes) {
this.totalIndexes = totalIndexes;
}
public int index() {
int currentIndex;
int nextIndex;
do {
currentIndex = atomicInteger.get();
nextIndex = currentIndex< Integer.MAX_VALUE ? currentIndex+1: 0;
} while (!atomicInteger.compareAndSet(currentIndex, nextIndex));
return nextIndex % totalIndexes;
}
}