1)双重检查概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if (singleton == null) 检查,这样就可以保证线程安全了
2)这样,实例化代码只用执行一次,后面再次访问时,判断if (singleton == null) ,直接return实际化对象,也避免的反复进行方法同步
3)线程安全、延迟加载、效率较高
4)结论:在实际开发中,推荐使用这种单例设计模式
public class SingletonTest06 {
public static void main(String[] args) {
Singleton06 instance = Singleton06.getInstance();
Singleton06 instance01 = Singleton06.getInstance();
System.out.println(instance == instance01);
System.out.println("instance,hashCode= " + instance.hashCode());
System.out.println("instance01,hashCode = " + instance01.hashCode());
}
}
class Singleton06 {
private static volatile Singleton06 singleton;
private Singleton06() {
}
public static Singleton06 getInstance() {
if (singleton == null) {
synchronized (Singleton06.class) {
if (singleton == null) {
singleton = new Singleton06();
}
}
}
return singleton;
}
}
// 运行结果
true
instance,hashCode= 1846274136
instance01,hashCode = 1846274136