JUC_08

1、CAS 比较当前工作内存中的值,如果这个值是期望的,就执行操作,否则一直循环。
缺点:1、循环会耗时。2、一次性只能保证一个共享变量的原子性。3、ABA问题。乐观锁
AtomicStampedReferenc
Integer 在-128至127之间是一个对象,否则就会重新创建一个。

点击查看代码
package org.li;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CAS {

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1,1);

    public static void main(String[] args) {
        new Thread(()->{
            int stamp=atomicStampedReference.getStamp();
            System.out.println("a1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("a1->"+atomicStampedReference.compareAndSet(1, 2, stamp, stamp + 1));
            System.out.println("a2->"+atomicStampedReference.getStamp());
            System.out.println("a2->"+atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a3->"+atomicStampedReference.getStamp());
        }).start();
        new Thread(()->{
            int stamp=atomicStampedReference.getStamp();
            System.out.println("b1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("b2->"+atomicStampedReference.compareAndSet(1, 2, stamp, stamp + 1));
             System.out.println("b3->"+atomicStampedReference.getStamp());
        }).start();
    }
}

运行结果:

点击查看代码
b1->1
a1->1
a1->true
a2->2
a2->true
a3->3
b2->false
b3->3
posted @ 2025-04-17 20:58  黑影五  阅读(8)  评论(0)    收藏  举报