关于静态内部类和内部类

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的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值