1、懒汉单例模式(不推荐用)

public class LazySingleton {
    private static LazySingleton lazySingleton = null;//定义类
    private LazySingleton(){
    }//私有构造器
    public static LazySingleton getInstance(){
        if(lazySingleton == null){
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }
}

适用单线程场景(对多线程不安全)

线程安全的懒汉单例模式

public class LazySingleton {
    private static LazySingleton lazySingleton = null;//定义类
    private LazySingleton(){
    }//私有构造器
    public synchronized static LazySingleton getInstance(){
        if(lazySingleton == null){
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }
}

等价写法:

public class LazySingleton {
    private static LazySingleton lazySingleton = null;//定义类
    private LazySingleton(){
    }//私有构造器
    public static LazySingleton getInstance(){
       synchronized { if(lazySingleton == null){
            lazySingleton = new LazySingleton();
           }
      }
        return lazySingleton;
    }
}

缺点synchronized 锁,锁住了类的全部资源,占用了资源

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容