public class TestAtomic {
public static void main(String[] args) {
AtomicInteger i=new AtomicInteger(0);
System.out.println(i.incrementAndGet());//1
System.out.println(updateAndGet(i,p -> p/2));
}
//模拟底层实现:
public static int updateAndGet(AtomicInteger i, IntUnaryOperator operator){
while(true){
int prev=i.get();//得到当前值
int next=operator.applyAsInt(prev);//将旧值传入,让接口的某个方法完成具体运算,返回计算结果
if(i.compareAndSet(prev,next)){
return next;
}
}
}
}
该方法实际的底层实现:
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();//获取
next = updateFunction.applyAsInt(prev);//更新
} while (!compareAndSet(prev, next));//比较并设置
return next;
}