1.使用原子类,不需要加锁也可以实现线程安全,避免synchronized高开销,提高效率[多线程插入属于归并结果用到] 2.原理:CAS+VOLATILE+NATIVE本地方法来保证原子性
package com.wlfy.www.exclusivelock;
import java.util.concurrent.atomic.AtomicInteger;
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
|