long object FieldOffset(Field field)方法, 负责获得指定变量在所属类中的内存偏移量,该偏移量只能在Unsafe方法中访问指定函数才能使用
long native getLongVolatile(Object obj,long offset)方法,负责获得对象obj中指定偏移量offset的变量所对应的值
AtomicLong
递增递减操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//获得递增后的值 public final long incrementAndGet() { return unsafe.getAndAddLong(this, valueOffset, 1L) + 1L; }
//获得递减后的值 public final long decrementAndGet() { return unsafe.getAndAddLong(this, valueOffset, -1L) - 1L; } //获得递增前的值 public final long getAndIncrement() { return unsafe.getAndAddLong(this, valueOffset, 1L); } 获得递减前的值 public final long getAndDecrement() { return unsafe.getAndAddLong(this, valueOffset, -1L); }
//参数一代表AtomicLong实例的引用, //参数二代表AtomicLong的value变量的偏移量 //参数三代表要改变的值 public final long getAndAddLong(Object var1, long var2, long var4) { long var6; do { var6 = this.getLongVolatile(var1, var2);//获得初始值 //如果获得的初始值不相等则继续循环直到相等 } while(!this.compareAndSwapLong(var1, var2, var6, var6 + var4));
public class TestAtomic { public static void main(String[] args) throws InterruptedException { for (int i=0;i<10;i++){ Thread thread=new Thread(new CountThread(),"线程"+i); thread.start(); thread.join(); } System.out.println(CountThread.value); } public static class CountThread implements Runnable{
public static AtomicLong value=new AtomicLong(); @Override public void run() { for (int i=0;i<1000;i++){ value.incrementAndGet(); } } } }