单例模式的介绍可参考
https://blog.youkuaiyun.com/SummerMangoZz/article/details/57080540
https://blog.youkuaiyun.com/qq_37520037/article/details/82719190
体会懒汉式的双重检测的好处
public static synchronized Singleton getInstance() {
if(uniqueInstance==null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
public static Singleton getInstance() {
if(uniqueInstance==null) {
synchronized (Singleton.class) {
if(uniqueInstance==null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
这两种写法都是线程安全的,但是效率上,后者明显优于前者。 直接对方法加锁会导致即使已经存在实例对象,仍要进行无意义的等待。