Java Unsafe类的使用
Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null); System.out.println(unsafe); User user = new User(1,"aa"); System.out.println("id=" + user.getId()); Field field = user.getClass().getDeclaredField("id"); long l = unsafe.objectFieldOffset(field); System.out.println(l); unsafe.compareAndSwapInt(user,l,1,2); System.out.println("id=" +user.getId()); public class User { private int id; private String name; public User(int id,String name) { this.id = id; this.name = name; } public int getId() { return id; } }
邮箱:wangh_2@sina.com