import sun.misc.Unsafe;
import java.io.Serializable;
import java.lang.reflect.Field;
public class MyAtomicInteger implements Serializable {
private static final long serialVersionUID = 6214790243416807051L;
private volatile Integer num;
public MyAtomicInteger(Integer num) {
this.num = num;
}
private Unsafe unsafe;
private Long numOffset;
{
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
numOffset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("num"));
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
public int getAndSet(int num) {
return unsafe.getAndSetInt(this, numOffset, num);
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, numOffset, expect, update);
}
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, numOffset, 1);
}
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, numOffset, -1);
}
public Integer get() {
return num;
}
public void set(Integer num) {
this.num = num;
}
}
自己实现一个AtomicInteger
最新推荐文章于 2023-08-29 16:43:34 发布