Atomic原子类使用总结

原子类的概念

java.util.concurrent.atomic

  • 不可分割

  • 一个操作是不可中断的,即便是多线程的情况下也可以保证

  • 原子类的作用与锁类似,是为了保证并发情况下线程安全。

原子类的优势
  • 粒度更细

    原子变量可以把竞争范围缩小到变量级别,这是我们可以获得的最细粒度的情况,通常锁的粒度都要大于原子变量的粒度

  • 效率更高

    使用原子类的效率会比使用锁的效率更高,除了高度竞争的情况

六大原子类纵览

在这里插入图片描述

Atomic*基本类型原子类
  • AtomicBoolean

  • AtomicInteger

  • AtomicLong

已AtomicInteger为例
常用方法
  • get()

    获取当前的值

  • getAndSet(int newValue)

获取当前的值,并设置新的值

  • getAndIncrement()

    获取当前的值,并自增

  • getAndDecrement()

    获取当前的值,并自减

  • getAndAdd(int delta)

    获取当前的值,并加上预期的值

  • compareAndSet(int expect,int update)

    如果当前的数值等于预期值,则以原子方式将该值设置为输入值

代码演示
public class AtomicIntegerDemo implements Runnable {
   


    private static final AtomicInteger atomicInt = new AtomicInteger();

    private static void getIncrement(){
   
        atomicInt.getAndIncrement();
        //atomicInt.getAndDecrement();
        //atomicInt.getAndAdd(-1);
        //atomicInt.getAndAdd(1);
    }

    private static volatile  int basicCount = 0;

    public static void basicCountAdd(){
   
        basicCount++;
    }

    @Override
    public void run() {
   
        for (int i = 0; i < 10000; i++) {
   
            getIncrement();
            basicCountAdd();
        }
    }

    public static void main(String[] args) throws InterruptedException {
   

        AtomicIntegerDemo atomicIntegerDemo = new   AtomicIntegerDemo();
        Thread thread1 = new Thread(atomicIntegerDemo);
        Thread thread2 = new Thread(atomicIntegerDemo);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(atomicInt.get()); //20000
        System.out.println(basicCount); //19518 (小于等于20000)

    }
}
Atomic*Array数组原子类
代码演示

以AtomicIntegerArray为例

public class AtomicArrayDemo {
   

    public static void main(String[] args) throws InterruptedException {
   
        AtomicIntegerArray array = new AtomicIntegerArray(1000);


        Decrement decrement = new Decrement(array);

        Increment increment = new Increment(array);


        Thread[] thread1 = new Thread[100];
        Thread[] thread2 = new Thread[100];

        for (int i = 0; i < thread1.length; i++) {
   
            thread1[i]</
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值