单例设计模式之懒汉式(线程安全)

package com.waibizi.demo04;


/**
 * 懒汉式线程安全写法
 * 优点:解决了线程不安全的问题
 * 缺点:效率太低了,每个线程在想获得类的实例的时候,执行getInstance()方法都要进行同步,而其实这个方法只执行一次实例化代码就可以了,后面的想获得该类实例的时候
 *            直接return即可了
 * 结论:在实际的开发中不推荐这种写法
 * @author 歪鼻子
 *
 */
public class Singleton_pattern {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Singleton test = Singleton.getInstance();
        Singleton test1 = Singleton.getInstance();
        System.out.println(test.hashCode());
        System.out.println(test1.hashCode());

    }

}
@SuppressWarnings("all")
class Singleton{
    private static Singleton instance;
    private Singleton() {
        
    }
    
    //提供一个静态的公有方法,当使用该方法时,才去创建instance
    //即懒汉式加载(线程安全)
    public static synchronized Singleton getInstance() {
        if(instance==null) {
            System.out.println("我只初始化了这一次哦");
            instance=new Singleton();
        }
        return instance;
    }
}

猜你喜欢

转载自www.cnblogs.com/waibizi/p/12079849.html