zoukankan      html  css  js  c++  java
  • CAS

    https://www.jianshu.com/p/8de8c6a839e8

    public class Automic1 {
    //AtomicInteger解决不了ABA问题,ABA问题可能在业务场景下会导致问题,例如一个人去取款,取款机因为特殊原因启动了两个线程,其中一个线程执行扣减成功,本来100块钱,结果取了50,账户应该剩余50块钱
    //线程2因为阻塞未扣减,此时若不存在线程三,则会扣减失败,但是若此时线程三是加上50块钱,线程三执行完成之后,线程2才去执行,此时线程2以为并未扣减,然后扣减,导致账户最终只有50块钱
    static AtomicInteger automic = new AtomicInteger(10);
    //可使用AtomicStampedReference来解决ABA问题,因为此加上了版本控制,每更新一次,会收到改变stamp的值7
    static AtomicStampedReference atomicStampedRef=new AtomicStampedReference(10,0);//加上了版本号控制,解决了ABA问题
    public static void main(String[] args) throws InterruptedException {
    Thread t1=new Thread(()->{
    automic.compareAndSet(10,11);
    automic.compareAndSet(11,10);
    });
    Thread t2=new Thread(()->{
    boolean c3=automic.compareAndSet(10,11);
    System.out.println(c3+""+automic.get());
    });

    t1.start();
    t2.start();
    t1.join();
    t2.join();
    Thread refT1 = new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
    }
    atomicStampedRef.compareAndSet(100, 101, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
    atomicStampedRef.compareAndSet(101, 100, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
    }});

    Thread refT2 = new Thread(new Runnable() {
    @Override
    public void run() {
    int stamp = atomicStampedRef.getStamp();
    try {
    TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
    }
    boolean c3 = atomicStampedRef.compareAndSet(100, 101, stamp, stamp + 1);
    System.out.println(c3); // false
    }
    });
    refT1.start();
    refT2.start();
    }
  • 相关阅读:
    windows基线检测脚本编写指南-powershell版
    2020蓝帽杯CTF Web 题
    2020天翼杯CTF Web 题
    Firefox 密码脱取
    利用iptables做端口转发
    Flask 快速学习笔记
    JSP无%%号命令执行一句话
    linux 后渗透凭据收集
    Fastjson漏洞利用
    Gogs远程命令执行利用
  • 原文地址:https://www.cnblogs.com/zpp1234/p/13098342.html
Copyright © 2011-2022 走看看