关于静态内部类和内部类

    技术2022-05-20  57

    public class Another { class Atom implements Runnable { public int i;   public Atom() { System.out.println("createAtom"); }   public void run() { synchronized (Atom.class) { StaticClass.run(); }   } }   static class StaticAtom implements Runnable { public int i;   public StaticAtom() { i++; System.out.println("creatoeStaticAtion"+i); }   /** * 静态内部类的调用是线程安全的 */ public void run() { StaticClass.run();   }   }   public static void main(String[] args) throws Exception { (new Another()).testSatic(); // Atom atom = new Atom(); 不能通过应为静态方法的调用没有实例,因为非静态内部类必须依赖外部的类的实例创建 for (int i = 0; i < 100; i++) { StaticAtom sa = new StaticAtom(); Thread t = new Thread(sa); t.start(); } }   public void testSatic() throws Exception { // StaticAtom sa =new StaticAtom(); 可以编译通过。非静态方法可以创建静态内部类的实例 for (int i = 0; i < 5; i++) { Atom atom = new Atom(); Thread t = new Thread(atom); t.start(); } } }

      public class StaticClass{ private static int i; private StaticClass() { } public static void run() { i++; System.out.println("类变量的值是"+i); }   }

    注意静态内部类的run调用不需要sync也是threadsafe的,内部类的run需要sync的。


    最新回复(0)