懒汉式(线程安全、同步方法)
优缺点说明:
1) 解决了线程不安全问题
2) 效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行
同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,
直接return就行了。方法进行同步效率太低
3) 结论:在实际开发中,不推荐使用这种方式
代码实现:
package com.it.singleton;
/*懒汉式(线程安全,同步方法)*/
public class Singleton4 {
/*提供静态对象实例*/
private static Singleton4 instance;
/*私有的构造器,外部不能new对象实例*/
private Singleton4(){
}
/*
* 加入synchronized关键字,提供一个静态公有同步方法,当使用该方法时,才去创建instance
* 解决线程安全问题
* 即懒汉式(线程安全,同步)
* */
public static synchronized Singleton4 getInstance(){
/*使用时才创建*/
if(instance == null){
instance = new Singleton4();
}
return instance;
}
}
测试:
package com.it.singleton.test;
import com.it.singleton.Singleton4;
public class SingletonTest4 {
public static void main(String[] args) {
Singleton4 instance1 = Singleton4.getInstance();
Singleton4 instance2 = Singleton4.getInstance();
System.out.println(instance1 == instance2);//true 同一对象
System.out.println(instance1.hashCode() == instance2.hashCode());//true
}
}