单例模式的饿汉式和懒汉式

使用单例模式,多个线程操作同一个对象,保证对象的唯一性

饿汉式

public class HungerySingleton {
    private static HungerySingleton instance = new HungerySingleton() ;
    private HungerySingleton(){}
    public static HungerySingleton getInstance(){
        return instance ;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                HungerySingleton instance = getInstance();
                System.out.println(instance);
            }).start();
        }
    }
}

饿汉式:线程安全,在加载的时候实例化,只有一次所以是安全的 。性能比较好。
饿汉式很简单就是类加载的时候就进行实例化。

懒汉式

单例中的懒汉式有几种写法,这里就写一个双重检验锁

public class DCL {
    private volatile static DCL instance = null ;
    private DCL(){}
    public static DCL getInstance(){
        if(null == instance) {
            synchronized (DCL.class) {
                if(instance == null) {
                    instance = new DCL() ;
                }
            }
        }
        return instance ;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                DCL instance = getInstance();
                System.out.println(instance);
            }).start();
        }
    }
}

这段代码跟小伙伴讨论了一下,下面说一下我的想法
在这里插入图片描述
这里只有两段简单的代码,如果如果有什么问题,请大家指教
单例模式还有Holder和枚举的写法,不太了解 ,所以就不写了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章