原子类的工具类包含下面:
常涉及到的方法:compareAndSet(); 先对比,后赋值,
举例 AtomicInteger :
AtomicInteger i = new AtomicInteger(); i.set(1); i.compareAndSet(2,3);//用2和1对比,返回false,所以不赋值 System.out.println(i.get());//结果:1 i.compareAndSet(1,3);//用1和1对比,返回true,然后进行赋值 System.out.println(i.get());//结果:3
内部实现:
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
是使用volatile作为关键字实现的