java.util.concurrent源码学习一

public class AtomicBoolean implements java.io.Serializable

一:作用

A  boolean  value that may be updated atomically

二:主要成员变量

    private static final Unsafe unsafe = Unsafe.getUnsafe();

       sun 提供进行一些非安全操作的类

    private static final long valueOffset;

       保存value属性在这个对象中内存位置的偏移量,unsafe对象中会使用该值

    private volatile int value;
       保存该对象的值,如果为true则value = 1 ,如果为false则value = 0;

        volatile表示在多线程的情况下,如果有线程在修改这个属性值,则别的线程读取该属性的值一定是修改完成后的值,保证了可见性


三:主要成员方法

    获得值

 

    /**
     * Returns the current value.
     *
     * @return the current value
     */
    public final boolean get() {
        return value != 0;
    }

  比较和替换

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }


设置值

    /**
     * Unconditionally sets to the given value.
     *
     * @param newValue the new value
     */
    public final void set(boolean newValue) {
        value = newValue ? 1 : 0;
    }


获得并设置新值

    /**
     * Atomically sets to the given value and returns the previous value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final boolean getAndSet(boolean newValue) {
        for (;;) {
            boolean current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值