AtomicBoolean的妙用

来源:互联网 发布:电子音乐制作软件水果 编辑:程序博客网 时间:2024/05/16 11:31

在开发中,经常要设置代码开关,通常的做法如下:

 //这是一个全局变量 boolean isStart = false;

然后在某一个需要设置开关的位置:

if(!isStart ){    isStart = true;    doSomething();}

显然这是线程不安全的,通过使用AtomicBoolean可以这样做:

private static AtomicBoolean isStart = new AtomicBoolean(false);

在开关位置:

    if(isStart.compareAndSet(false, true) )    {        doSomething();    }

compareAndSet是基于CAS的原子操作,是线程安全的,参照jdk源码的描述:

/** * 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);}

如果isStart 和expect值相同,则设置isStart 为update值,并返回true,否则返回false。

0 0
原创粉丝点击