AtomicInteger

  • 注意value是volatile修饰的

image.png

Unsafe

image.png
JDK自带的底层实现,不允许开发者直接调用。只允许bootstrap类加载器加载。调用C++本地方法去执行。

getAndSet

compareAndSet

updateAndGet

  1. public static void main(String[] args) {
  2. AtomicInteger i = new AtomicInteger(5);
  3. /*System.out.println(i.incrementAndGet()); // ++i 1
  4. System.out.println(i.getAndIncrement()); // i++ 2
  5. System.out.println(i.getAndAdd(5)); // 2 , 7
  6. System.out.println(i.addAndGet(5)); // 12, 12*/
  7. // 读取到 设置值
  8. // i.updateAndGet(value -> value * 10);
  9. System.out.println(updateAndGet(i, p -> p / 2));
  10. // i.getAndUpdate()
  11. System.out.println(i.get());
  12. }
  13. //模拟updateAndGet
  14. public static int updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
  15. while (true) {
  16. int prev = i.get();
  17. int next = operator.applyAsInt(prev);
  18. if (i.compareAndSet(prev, next)) {
  19. return next;
  20. }
  21. }
  22. }
  23. }