import lombok.SneakyThrows;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
private static final AtomicInteger atomicInteger = new AtomicInteger(0);
@SneakyThrows
public static final int getAndIncrement() {
int current;
int next = 0;
do {
current = atomicInteger.get();
TimeUnit.SECONDS.sleep(2);
// 防止越界
next = current >= Integer.MAX_VALUE ? 0 : current + 1;
} while (!atomicInteger.compareAndSet(current, next));
System.out.println("next=" + next);
return next;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(AtomicIntegerTest::getAndIncrement).start();
}
}
}