Java并发编程——Atomic基本类型

本文介绍了Java并发编程中的Atomic基本类型,重点讲解了AtomicInteger的使用和底层实现原理。通过示例展示了AtomicInteger如何解决线程安全问题,并探讨了原子类的ABA问题及其解决方案。
摘要由CSDN通过智能技术生成

一. Atomic基本类型

1.基本数据类型

  • AtomicInteger
  • AtomicLong
  • AtomicBoolean

2.常用方法

  • int get() // 获取当前值
  • int getAndSet(int value) // 获取当前值并设置成指定值等价于普通变量的i = value
  • int getAndIncrement() // 自增 ,等价于普通变量的i++
  • int getAndDecrement() // 自减,等价于普通变量的i–
  • int getAndAdd(int Value) // 加上预期值,等价于普通变量的i = i + value
  • boolean compareAndSet(int expect, int update) //如果该对象等于期望值,把它更新成update的值,等价于普通变量的`if (i == expect) {i = update}

二. AtomicInteger

  • AtomicInteger 底层采用的是CAS原理(CompareAndSwap)。AtomicInteger 类型的对象,之所以在对AtomicInteger对象操作时,能保证线程安全,是因为在进行操作时,会将当前对象的值与内存中变量的值进行比较,如果是一致的,则进行变量操作,否则继续去内存中获取变量的值,直至当前值,与内存中的值是一致的。
  • AtomicInteger 对象,可以通过调用incrementAndGet()方法和getAndIncrement()方法进行值加1的操作,区别在于:incrementAndGet()方法先执行加1操作,然后获取值;getAndIncrement()方法是先获取值然后执行加1的操作;

三. AtomicInteger 对象使用示例:

1.非线程安全的使用示例:

@Slf4j
public class CountExample1 {
   

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static int count = 0;

    public static void main(String[] args) throws Exception {
   
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ;</
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值