1.使用原子类,不需要加锁也可以实现线程安全,避免synchronized高开销,提高效率[多线程插入属于归并结果用到]
2.原理:CAS+VOLATILE+NATIVE本地方法来保证原子性
package com.wlfy.www.exclusivelock;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author wl
* @description AtomicIntegerTest
* @date 2022/4/6 19:30
*/
public class AtomicIntegerTest {
public static void main(String[] args) {
testABA();
testAtomicInteger();
}
private static void testAtomicInteger() {
int temValue = 0;
AtomicInteger atomicInteger = new AtomicInteger(9);
//获取当前值并且设置新的值
temValue = atomicInteger.getAndSet(3);
System.out.println(temValue + ":" + atomicInteger);
//获取当前值并自增
temValue = atomicInteger.getAndIncrement();
System.out.println(temValue + ":" + atomicInteger);
//获取当前值并加上预期的值
temValue = atomicInteger.getAndAdd(5);
System.out.println(temValue + ":" + atomicInteger);
}
public static void testABA() {
final AtomicInteger atomicInteger = new AtomicInteger(1);
new Thread(() -> {
final int currentValue = atomicInteger.get();
System.out.println(Thread.currentThread().getName() + "--- currentValue=" + currentValue);
//模拟处理其他业务花费的时间
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean casRest = atomicInteger.compareAndSet(1, 2);
System.out.println(Thread.currentThread().getName() + "--- currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get() + ", compareAndSet casRest=" + casRest);
}).start();
//让上面线程先跑起来
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
int currentValue = atomicInteger.get();
boolean casRest = atomicInteger.compareAndSet(1, 2);
System.out.println(Thread.currentThread().getName() + "--- currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get() + ", compareAndSet casRest=" + casRest);
currentValue = atomicInteger.get();
casRest = atomicInteger.compareAndSet(2, 1);
System.out.println(Thread.currentThread().getName() + "--- currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get() + ", compareAndSet casRest=" + casRest);
}).start();
}
}
结果:
Thread-0--- currentValue=1
Thread-0--- currentValue=1, finalValue=2, compareAndSet casRest=true
9:3
3:4
4:9
Thread-1--- currentValue=2, finalValue=2, compareAndSet casRest=false
Thread-1--- currentValue=2, finalValue=1, compareAndSet casRest=true