- package thread;
- import java.lang.reflect.Field;
- import sun.misc.Unsafe;
- public class Test {
-
- public static void main(String[] args) throws Exception {
- System.out.println(A.flag);
- new A();
- new A();
- System.out.println(A.flag);
- }
- }
- class A
- {
- public static final boolean flag=false;
- public A() throws Exception
- {
- if(getflag()) throw new Exception();
- getUnsafe().putBooleanVolatile(A.class, getUnsafe().staticFieldOffset(A.class.getField("flag")), true);
- }
- private static final Unsafe getUnsafe()
- {
- Unsafe unsafe=null;
- try{
- Field field= Unsafe.class.getDeclaredField("theUnsafe");
- field.setAccessible(true);
- unsafe=(Unsafe)field.get(Unsafe.class);
- }
- catch(Exception e){}
- return unsafe;
- }
- private static final boolean getflag()
- {
- boolean b = false;
- try{
- long start= getUnsafe().staticFieldOffset(A.class.getField("flag"));
- b=getUnsafe().getBooleanVolatile(A.class, start);}
- catch(Exception e){}
- return b;
- }
- }
复制代码 |
|