AtomicBoolean源码解析

来源:互联网 发布:藤县网络电视 编辑:程序博客网 时间:2024/05/21 20:17

再看AsyncTask时使用到了此类,就顺手研究了一下

AtomicBoolean 比较简单的一个类,但是好处多多. 使用起来比较方便先介绍一下他的好处

它主要的作用是用来作判断使用的,这里很多人就有疑问为什么不使用boolean 变量下面就是它的好处

1.它支持线程同步  

private volatile int value;

2.它支持跨进程

public class AtomicBoolean implements java.io.Serializable 

使用起来也比较简单 一个指定默认值一个不指定默认值

/** * Creates a new {@code AtomicBoolean} with the given initial value. * * @param initialValue the initial value */public AtomicBoolean(boolean initialValue) {    value = initialValue ? 1 : 0;}/** * Creates a new {@code AtomicBoolean} with initial value {@code false}. */public AtomicBoolean() {}

改变状态

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

获取状态

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

其他类似类 AtomicBoolean,AtomicInteger,AtomicIntegerArray,AtomicLong,AtomicLongArray 等等  



原创粉丝点击