一、懒汉式单例模式
懒汉式单例模式在被外部类调用时创建实例,因类加载速度快,但运行时获取对象的速度慢
二、实例
1、懒汉式1(线程不安全)
public class LazySingleton{
private static LazySingleton instance;
private LazySingleton(){}
public static LazySingleton getInstance(){
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
}
这种方式起到懒加载的效果,但只能在单线程下使用,如果在多线程下,一个线程进入if(instance == null)判断语句块,还没有执行产生实例的语句,另一个线程又进来,这时会产生多个实例,所以不安全。
2、懒汉式2(使用synchronized同步,线程安全)
在方法上使用synchronized锁进行同步,优点解决了线程不安全的问题,缺点是这个同步方法影响的区域太大,如果多个对象想获取这个对象的时候会柱塞在这排队,效率太低了。
public class LazySingleton{
private static LazySingleton intance =null;
private LazySingleton(){}
public static synchronized LazySingleton getInstance(){
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
}
3、懒汉式3 同步代码块(线程安全)
同步代码块保证线程安全但是不满足单例,在多线程下依旧会有多个实例
public class LazySingleton{
private static LazySingleton instance = null;
private LazySingleton(){}
public static LazySingleton getInstance(){
if(instance == null){
synchronized(LazySingleton.class){
instance = new LazySingleton();
}
}
return instance;
}
}
参考文章:
https://blog.youkuaiyun.com/qq_44543508/article/details/103249751
synchronized:https://blog.youkuaiyun.com/zjy15203167987/article/details/82531772