关于双重检验锁方法和内部类方法实现单例模式的实验

网上很多人说,使用双重检验锁方法实现单例模式可能会new多个实例,而内部类方法和枚举类方法完美解决了这个问题

因为Android很少使用枚举,本次只研究双重检验锁方法和内部类方法

双重检验锁方法:

代码如下:

public class SingletonB {
    private static volatile SingletonB mInstance;

    private SingletonB() {
        System.out.println("双重检验锁方法单例模式");
    }

    public static SingletonB getInstance() {
        if (mInstance == null) {
            synchronized (SingletonB.class) {
                if (mInstance == null) {
                    mInstance = new SingletonB();
                }
            }
        }
        return mInstance;
    }
}

内部类方法:

代码如下:

public class SingletonA {
    private SingletonA() {
        System.out.println("内部类方法单例模式");
    }

    private static class Singleton {
        private static final SingletonA INSTANCE = new SingletonA();
    }

    public static SingletonA getInstance() {
        return Singleton.INSTANCE;
    }
}

在多线程环境下分别使用这两种单例模式

测试代码:

public class Test {

    public static void main(String[] args) {
        Thread[] threads = new Thread[10000];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread() {
                public void run() {
                    SingletonA.getInstance();
                    SingletonB.getInstance();
                };
            };
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
    }

}

运行结果

运行了N次,两个单例模式都是只运行了一次构造函数。

其实我的期望是能出现双重锁方法的bad case,但是并没有出现。本次实验失败,下次再接再厉。

转载于:https://www.cnblogs.com/shenchanghui/p/9114283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值