我想知道原子类中 set() 和 compareAndSet() 之间的区别。set() 方法是否也确保原子过程?例如这段代码:
public class sampleAtomic{
private static AtomicLong id = new AtomicLong(0);
public void setWithSet(long newValue){
id.set(newValue);
}
public void setWithCompareAndSet(long newValue){
long oldVal;
do{
oldVal = id.get();
}
while(!id.compareAndGet(oldVal,newValue)
}
}
这两种方法是否相同?