CAS中的ABA问题

ABA问题描述

第一个线程取到了变量 x 的值 A,然后开始做其他的业务逻辑,总之就是只拿到了变量 x 的值 A。这段时间内第二个线程也取到了变量 x 的值 A,然后把变量 x 的值改为 B,然后做了一些事情,最后又把变量 x 的值变为 A (相当于还原了)。在这之后第一个线程结束了它的业务逻辑,终于进行了变量 x 的操作,但是此时变量 x 的值还是 A,所以 compareAndSet 操作是成功。 这就是CAS中的ABA问题。

ABA问题代码


```java
public class ABAProblemTest {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(1);
        new Thread(()->{
            int curval = atomicInteger.get();
            System.out.println(Thread.currentThread().getName() + " ------ currentValue=" + curval);
            // 模拟处理业务逻辑
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean setResult = atomicInteger.compareAndSet(1, 2);
            System.out.println(Thread.currentThread().getName()
                    + "----- currentValue=" + curval
                    + ",----- finalValue=" + atomicInteger.get()
                    + ",----- compareAndSet Result=" + setResult);
        }).start();
        //保证上面的线程先启动
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            // 先设置为2 又设置回1
            int curval = atomicInteger.get();
            boolean casResult = atomicInteger.compareAndSet(1, 2);
            System.out.println(Thread.currentThread().getName()
                    + "----- currentValue=" + curval
                    + ",----- finalValue=" + atomicInteger.get()
                    + ",----- compareAndSet Result=" + casResult);

            curval = atomicInteger.get();
            casResult = atomicInteger.compareAndSet(2, 1);
            System.out.println(Thread.currentThread().getName()
                    + "----- currentValue=" + curval
                    + ",----- finalValue=" + atomicInteger.get()
                    + ",----- compareAndSet Result=" + casResult);
        }).start();
    }
}

## 输出结果

```powershell
Thread-0 ------ currentValue=1
Thread-1----- currentValue=1,----- finalValue=2,----- compareAndSet Result=true
Thread-1----- currentValue=2,----- finalValue=1,----- compareAndSet Result=true
Thread-0----- currentValue=1,----- finalValue=2,----- compareAndSet Result=true

分析

可以看到atomicInteger被线程1线程修改过,这个过程线程0并不知道,导致最终线程0能够成功修改。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值