优缺点说明
1)解决了线程不安全问题
2)效率太低了。每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了。方法进行同步效率太低
3)结论:在实际开发种,不推荐使用这种方式
代码语言:javascript复制public class SingletonTest03 {
public static void main(String[] args) {
Singleton03 instance = Singleton03.getInstance();
Singleton03 instance01 = Singleton03.getInstance();
System.out.println(instance == instance01);
System.out.println("instance,hashCode= " instance.hashCode());
System.out.println("instance01,hashCode= " instance01.hashCode());
}
}
class Singleton03{
private static Singleton03 instance;
private Singleton03(){}
public static synchronized Singleton03 getInstance(){
if(instance == null){
instance = new Singleton03();
}
return instance;
}
}
// 运行结果
true
instance,hashCode= 1846274136
instance01,hashCode= 1846274136