zoukankan      html  css  js  c++  java
  • AtomicBoolean与AtomicInteger学习

    AtomicBoolean跟AtomicInteger都有一个compareAndSet的方法

    public final boolean compareAndSet(boolean expect, boolean update)
    public final boolean compareAndSet(int expect, int update)
    

    我网上看见compareAndSet的应用可以是防止多次初始化,比如多个线程想用compareAndSet来判断是否初始化过,只有一个线程能初始化

    public final boolean getAndSet(boolean newValue) {
            for (;;) {
                boolean current = get();
                if (compareAndSet(current, newValue))
                    return current;
            }
        }
    

    当然AtomicBoolean最重要的就是getAndSet可以保证多个线程原子的更新值,可以看见代码是不停的检查,如果符合期望值就可以更新

    public final int getAndIncrement() {
            for (;;) {
                int current = get();
                int next = current + 1;
                if (compareAndSet(current, next))
                    return current;
            }
        }
    

    AtomicInteger可以保证多个线程原子的加1,可以当计数器用。代码里不停的用checkAndSet来实现。

  • 相关阅读:
    私有 composer 包创建
    随机数是如何生成的
    TCP 三次握手的意义
    何为真何为假
    Python流程控制语句详解
    Python类中装饰器classmethod,staticmethod,property,
    函数进阶
    初识函数
    文件操作
    is ==小数据池编码解码
  • 原文地址:https://www.cnblogs.com/encode/p/5913046.html
Copyright © 2011-2022 走看看