// 懒汉式(线程安全,同步方法)
class Singleton {
private static Singleton instance;
private Singleton() {}
//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
//即懒汉式
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
因为new语句只需要被调用一次,而上面的方法每次被调用都需要线程锁,导致消耗太大。
尚硅谷Java设计模式(图解+框架源码剖析)p33
// 懒汉式(线程安全,同步方法)
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
在进入锁之前,new语句可能已被其他线程执行,由此认为上面的写法是线程不安全的,在进入锁之后,判断单例是否依然为空,从而决定是否执行new语句。
尚硅谷Java设计模式(图解+框架源码剖析)p34
// 懒汉式(线程安全,同步方法)
class Singleton {
// volatile关键字保证可见性(并发编程:可见性,原子性,有序性)
private static volatile Singleton instance;
private Singleton() {}
//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
//同时保证了效率, 推荐使用
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}