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

package com.waibizi.demo03;
/**
 * 优点:起到了懒加载的效果,但是只能在单线程的情况下使用
 * 缺点:如果是多线程下,一个线程已经进入了if(instance==null) 但是还没来得及实例化,这时候另外一个线程也进入了if(instance==null) ,这时便会产生多个实例
 *            所以在多线程的情况下不能使用这种懒汉式加载
 * @author 歪鼻子
 *
 */
@SuppressWarnings("all")
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 Singleton getInstance() {
        if(instance==null) {
            System.out.println("我只初始化了这一次哦");
            instance=new Singleton();
        }
        return instance;
    }
}

猜你喜欢

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