Java线程安全基础类型

在java1.5加入了Atomic这个帮助类型。在java.util.concurrent.atomic。这里的atomic是线程安全的基本数据类型。去sun官网下载最新api文档就能看到。这里我给大家简单介绍一下Atomic系列的数据类型。先看看sun对atomic包的简介:
A small toolkit of classes that support lock-free thread-safe programming on single variables
大概意思是支持单个变量线程安全编程的一个小工具箱。atomic系列包含以下数据类型。

AtomicBoolean
AtomicInteger
AtomicIntegerArray
AtomicIntegerFieldUpdater
AtomicLong
AtomicLongArray
AtomicLongFieldUpdater
AtomicMarkableReference
AtomicReference
AtomicReferenceArray
AtomicReferenceFieldUpdater
AtomicStampedReference
DoubleAccumulator
DoubleAdder
LongAccumulator
LongAdder

AtomicBoolean

构造函数

AtomicBoolean() 创建一个新的 AtomicBoolean 初始化为默认 false.
AtomicBoolean(boolean initialValue) 创建一个新的 AtomicBoolean使用参数进行初始化.

具体方法

  1. boolean compareAndSet(boolean expect, boolean update)
    先进行判断,如果当前atomicboolean的value == expect,那么就会自动设置当前atomicboolean的value=update。返回值是expect和value的比较。
  2. boolean get() 返回当前对象的boolean值
  3. boolean getAndSet(boolean newValue) 先返回当前对象的value,在设置新的值给当前对象。
  4. void set(boolean newValue) 设置当前对象的值
  5. boolean weakCompareAndSet(boolean expect, boolean update) 先进行判断,如果当前atomicboolean的value == expect,那么就会自动设置当前atomicboolean的value=update。返回值是expect和value的比较。

AtomicInteger

构造函数

AtomicInteger() 创建一个新的 AtomicBoolean 初始化为默认 0.
AtomicInteger(int initialValue)创建一个新的 AtomicInteger使用参数进行初始化.

具体方法

  1. int addAndGet(int delta) 先加上delta,在返回当前对象值,有点像++i
  2. boolean compareAndSet(int expect, int update) 先比较当前value == expect,如果是true,则自动更新当前value为update。返回value == expect的值
  3. int decrementAndGet() 自减1,返回结果
  4. double doubleValue() 当前值转换为double并返回
  5. float floatValue() 当前值转换为float 并返回
  6. int get() 获取当前对象值
  7. int getAndAdd(int delta) 先获得当前值,再加上delta赋给当前对象
  8. int getAndDecrement() 先获得当前值,再自动减1
  9. int getAndIncrement() 先获得当前值,再自动加1
  10. int getAndSet(int newValue) 先获取当前值,在设置当前值为newValue
  11. int incrementAndGet() 自加1,然后在返回当前值
  12. int intValue() 返回当前int基本数据类型值,包装类对应的基本数据类型
  13. void set(int newValue) 设置当前值
#例:
public static void main(String[] args) throws InterruptedException {
      AtomicInteger k = new AtomicInteger(0);
      final CountDownLatch latch = new CountDownLatch(100);

            for(int i=0;i<100;i++){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        k.getAndAdd(1);
                        latch.countDown();
                    }
                }).start();
            }
            latch.await();

            System.out.println("运行结果:"+k);
        }
        
        运行结果:100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值