原创

原子类

温馨提示:
本文最后更新于 2025年06月04日,已超过 373 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

volatile解决多线程内存不可见的问题对于一写多读,是可以解决变量同步问题,但是如果多写,同样无法解决线程安全问题

说明:count++操作,使用如下类实现

        AtomicInteger integer = new AtomicInteger();
        integer.addAndGet(1);

r如果是JDK8,推荐使用LongAdder对象,比AtomicLong性能更好(减少乐观锁的重试次数)


countdownlatch 配合 原子解决多线程问题

  • 基本类型原子类

AtomicInteger
AtomicBoolean
AtomicLong

class MyNumber {

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlus() {
        atomicInteger.getAndIncrement();
    }

}
 public static final int SIZE = 50;
MyNumber myNumber = new MyNumber();
        CountDownLatch downLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        myNumber.addPlus();
                    }
                } finally {
                    downLatch.countDown();
                }

            }, String.valueOf(i)).start();
        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("最终结果:" + Thread.currentThread().getName() + "  " + myNumber.atomicInteger.get());
  • 数组类型原子类

 AtomicIntegerArray

 AtomicLongArray

AtomicReferenceArray

引用类型原子

AtomicRefence

AtomicStampedRefence

AtomicMarkbleRefence   原子更新带有标记位的引用类型对象。状态戳(true/false)原子引用

  • 对象的属性修改原子类

 AtomicIntegerFieldUpdater

 AtomicLongFieldUpdater

AtomicReferenceFieldUpdater

  • 增强类原理深度解析

DoubleAccumulator

DoubleAdder

LongAccumulator

LongAdder









正文到此结束