
1 public class myTest { 2 long count = 0; 3 void add(){ 4 int idx = 0; 5 while(idx++ < 100000) { 6 count += 1; 7 } 8 }
}
1 public class myTest { 2 AtomicLong count = new AtomicLong(0); 3 void add(){ 4 int idx = 0; 5 while(idx++ < 100000) { 6 count.getAndIncrement(); 7 } 8 } 9 }

Unsafe提供了三个方法用于CAS操作,分别是
1 public final native boolean compareAndSwapObject(Object value, long valueOffset, Object expect, Object update); 2 3 public final native boolean compareAndSwapInt(Object value, long valueOffset, int expect, int update); 4 5 public final native boolean compareAndSwapLong(Object value, long valueOffset, long expect, long update);
Unsafe.objectFieldOffset(Field valueField)获取)
public static void main(String[] args) {
long count = 0;
int idx = 0;
while(idx++ < 10000) {
count += 1;
}
System.out.println(count);
}
原文:https://www.cnblogs.com/amberJava/p/12390917.html