zoukankan      html  css  js  c++  java
  • 并发编程之深入理解CAS

    public class ABADemo {
    private static AtomicReference atomicReference=new AtomicReference<>(100);
    private static AtomicStampedReference stampedReference=new AtomicStampedReference<>(100,1);
    public static void main(String[] args) {
    System.out.println("=以下是ABA问题的产生=");
    new Thread(()->{
    atomicReference.compareAndSet(100,101);
    atomicReference.compareAndSet(101,100);
    },"t1").start();

        new Thread(()->{
            //先暂停1秒 保证完成ABA
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(atomicReference.compareAndSet(100, 2019)+"	"+atomicReference.get());
        },"t2").start();
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("===以下是ABA问题的解决===");
    
        new Thread(()->{
            int stamp = stampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"	 第1次版本号"+stamp+"	值是"+stampedReference.getReference());
            //暂停1秒钟t3线程
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
    
            stampedReference.compareAndSet(100,101,stampedReference.getStamp(),stampedReference.getStamp()+1);
            System.out.println(Thread.currentThread().getName()+"	 第2次版本号"+stampedReference.getStamp()+"	值是"+stampedReference.getReference());
            stampedReference.compareAndSet(101,100,stampedReference.getStamp(),stampedReference.getStamp()+1);
            System.out.println(Thread.currentThread().getName()+"	 第3次版本号"+stampedReference.getStamp()+"	值是"+stampedReference.getReference());
        },"t3").start();
    
        new Thread(()->{
            int stamp = stampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"	 第1次版本号"+stamp+"	值是"+stampedReference.getReference());
            //保证线程3完成1次ABA
            try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
            boolean result = stampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName()+"	 修改成功否"+result+"	最新版本号"+stampedReference.getStamp());
            System.out.println("最新的值	"+stampedReference.getReference());
        },"t4").start();
    }
  • 相关阅读:
    MSP430的IAP程序在线编程学习
    新手入门Underscore.js 中文(template)
    关于javascript中的变量声明与赋值
    DOJO复选框操作
    添加.MSPX文件(VISTA下)
    TFS集合创建
    ExtJS的导航栏(Accordion TreePanel)
    新的开始,新的起点
    MongoDB实践之路安装
    检测一个文件是否正在使用
  • 原文地址:https://www.cnblogs.com/pengcode/p/15516576.html
Copyright © 2011-2022 走看看