其他分享
首页 > 其他分享> > cas 代码

cas 代码

作者:互联网

public class CounterUnsafe {
volatile int i = 0;

private static Unsafe unsafe = null;

//i字段的偏移量
private static long valueOffset;

static {
//unsafe = Unsafe.getUnsafe();
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);

Field fieldi = CounterUnsafe.class.getDeclaredField("i");
valueOffset = unsafe.objectFieldOffset(fieldi);

} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}


public void add() {
//i++;
for (;;){
int current = unsafe.getIntVolatile(this, valueOffset);
if (unsafe.compareAndSwapInt(this, valueOffset, current, current+1))
break;
}
}
}


public class Demo1_CounterTest {

public static void main(String[] args) throws InterruptedException {
final CounterUnsafe ct = new CounterUnsafe();

for (int i = 0; i < 6; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
ct.add();
}
System.out.println("done...");
}
}).start();
}

Thread.sleep(6000L);
System.out.println(ct.i);
}
}

标签:valueOffset,cas,代码,CounterUnsafe,unsafe,int,static,public
来源: https://www.cnblogs.com/wscp/p/16101830.html