import sun.misc.Unsafe; import java.lang.reflect.Field; public class LockDemo { volatile int i = 0; //类似操作内存的方法 static Unsafe unsafe = null; private static long iOffset; static { try { //反射技术拿到Unsafe对象 Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); unsafe = (Unsafe) theUnsafe.get(null); //利用unsafe.通过属性的偏离量(定位到内存中对象内具体属性的内存地址) iOffset = unsafe.objectFieldOffset(LockDemo.class.getDeclaredField("i")); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public void add(){ int current; int newi; // i++;存在 原子问题(通过do...while循环解决原子问题的i++) do { //根据内存对象的属性的相对地址获取i的值 current = unsafe.getIntVolatile(this,iOffset); newi = current + 1; //根据CAS机制判断如果获取的值已经改变则变更失败,重新获取变更 } while (!unsafe.compareAndSwapInt(this,iOffset,current,newi)); } public static void main(String[] args) throws InterruptedException { LockDemo ld = new LockDemo(); for (int i = 0; i < 2; i++){ new Thread(){ @Override public void run() { for (int j = 0; j < 1000; j++){ ld.add(); } } }.start(); } Thread.sleep(1000); System.out.println(ld.i); } }
java多线程 用Unsafe实现原子性
最新推荐文章于 2022-01-25 18:46:38 发布