首页 > 编程语言 > 详细

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

时间:2019-12-22 16:00:16      阅读:86      评论:0      收藏:0      [点我收藏+]
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();

        //线程安全不能用的方式
        // synchronized(Singleton.class) {
        // instance=new Singleton();
        // }


        }
        return instance;
    }
}

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

原文:https://www.cnblogs.com/waibizi/p/12079849.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!