原子类也是 JUC 包下的:java.util.concurrent.atomic
包含四个原子类:
- AtomicInteger
- AtomicLong
- AtomicBoolean
- AtomicRefence
Atomic
Atomic 的四个类型
- 基本数据类型
- 数组类型
- 引用类型
- 对象的属性修改类型
原子引用
解决 ABA 问题,引入原子引用,对应的引用:乐观锁
问题描述:
两个线程同时调用同一个共享信息,某一个执行完一次修改了原值,之后再修改为初始值,此时 其他线程不知道该共享值已经被修改过了,不是原先的值。
package pers.vincent.matrix.subject.atomic;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
public class AtomicDemo {
public static void main(String[] args) {
AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference(7, 1);
new Thread(() -> {
int stam = atomicStampedReference.getStamp();
System.out.println("A线程第一个版本号:" + stam);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicStampedReference.compareAndSet(7, 8, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
System.out.println("A1==" + atomicStampedReference.getStamp());
atomicStampedReference.compareAndSet(8, 7, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
System.out.println("A2==" + atomicStampedReference.getStamp());
}, "A").start();
new Thread(() -> {
int stam = atomicStampedReference.getStamp();
System.out.println("B线程第一个版本号:" + stam);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicStampedReference.compareAndSet(7, 8, stam, stam + 1));
System.out.println("B线程第二个版本号:" + atomicStampedReference.getStamp());
}, "B").start();
}
}