标签:java
原子更新
回顾使用
Aotimic使用(自增,自减都为原子操作)
private static AtomicLong atomicLong=new AtomicLong(0);
private static Random random=new Random(47);
private static StampedLock stampedLock=new StampedLock();
/**
* Aotimic使用(自增,自减都为原子操作)
* 线程操作:将随机值赋值给atomicLong
* 多个线程操作时,每个线程都会以乐观操作的方式更新值,直到CAS操作成功
*/
private void AtomicDemo(){
for(int i=0;i<10;i++){
new Thread(()->{
long oldValue;
long randomLong;
do{
oldValue=atomicLong.get();
randomLong=random.nextLong();
//不断循环,直到CAS操作成功
}while (!atomicLong.compareAndSet(oldValue,randomLong));
}).start();
}
}
LongAdder,LongAccumulator && DoubleAdder,DoubleAccumulator