JUC-java.util.concurrent.atomic包

一 AtomicInteger

public class AtomicIntegerExample{

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count.get());
    }

    private static void add() {
        count.incrementAndGet();
        // count.getAndIncrement();
    }
}
cas原理完成原子性(compareAndSwapInt)

在这里插入图片描述
在这里插入图片描述
主要是执行了一个do-while循环,compareAndSwapInt(var1,var2,var5,var5+var4)
说明:var1是传入的AtomicInteger对象,var2是当前值,var4是要增加的值,比如1,var5是当前底层主内存的值,如果var2和var5值相等时,执行var5加上var4,否则不断循环判断。

二 AtomicLong和LongAdder

AtomicLong是在一个死循环里保证安全性,竞争不激烈的情况下成功概率很高。准确数值的时候
LongAdder:统计数据会有误差,高并发效率高

三 AtomicReference和 AtomicIntegerFieldUpdater

public class AtomicReferenceExample{

    private static AtomicReference<Integer> count = new AtomicReference<>(0);

    public static void main(String[] args) {
        count.compareAndSet(0, 2); // 2
        count.compareAndSet(0, 1); // no
        count.compareAndSet(1, 3); // no
        count.compareAndSet(2, 4); // 4
        count.compareAndSet(3, 5); // no
        log.info("count:{}", count.get());
    }
}

更新某个类的字段,要求字段是非static,volatile修饰

public class AtomicExample5 {

    private static AtomicIntegerFieldUpdater<AtomicExample5> updater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    @Getter
    public volatile int count = 100; 

    public static void main(String[] args) {

        AtomicExample5 example5 = new AtomicExample5();

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 1, {}", example5.getCount());
        }

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 2, {}", example5.getCount());
        } else {
            log.info("update failed, {}", example5.getCount());
        }
    }
}

四 AtomicStampReference和AtomicMarkableReference:CAS的ABA问题

Thread1:A->B-A
Thead2:A->C
ABA问题:和我们数据库中用的多版本并发控制,使用乐观锁加一个 version 字段类似,比如InnoDB每一行会保存一个创建和删除的版本号,数据查询的时候会根据这两个版本号查询。
场景:
一个链表A-B-C,线程1准备将链表头结点换成B,执行CAS操作head.compareAndSet(A,B); 在执行该语句之前,线程2介入,并通过CAS操作将
head.compareAndSet(B,C); 此时链表为A-C,B节点被拿出了此时切回线程1,线程1发现,A没有发生改变还是A,则将A换成了B,此时B-next为null,节点C也被无辜删除了。总结来说就是:链表的改变没有在head上反映出来,head没有改变,但是链表却改变了。

AtomicStampedReference 中的版本号 stamp 是一个 int 类型
AtomicMarkableReference 中的版本号 mark 则是一个 boolean 类型

五 AtomicLongArray 数组 索引

六 AtomicBoolean

某一段代码执行一次

public class AtomicBooleanExample {

    private static AtomicBoolean isHappened = new AtomicBoolean(false);

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("isHappened:{}", isHappened.get());
    }

    private static void test() {
        if (isHappened.compareAndSet(false, true)) {
            log.info("execute");
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值