单例模式------懒汉式( 线程不安全)

懒汉式( 线程不安全) 优缺点说明: 1) 起到了Lazy Loading的效果,但是只能在单线程下使用。 2) 如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及 往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以 在多线程环境下不可使用这种方式 3) 结论:在实际开发中,不要使用这种方式.

实现代码:

package com.it.singleton;

/*懒汉式(非线程安全)*/
public class Singleton3 {

    /*提供静态对象实例*/
    private static Singleton3 instance;

    /*私有的构造器,外部不能new对象实例*/
    private Singleton3(){

    }

    /*
    *   提供一个静态公有方法,当使用该方法时,采取创建instance
    *   即懒汉式
    * */
    public static Singleton3 getInstance(){

        /*使用时才创建*/
        if(instance == null){
            instance = new Singleton3();
        }
        return instance;
    }
}

测试:

package com.it.singleton.test;

import com.it.singleton.Singleton3;

public class SingletonTest3 {

    public static void main(String[] args) {

        Singleton3 instance1 = Singleton3.getInstance();
        Singleton3 instance2 = Singleton3.getInstance();

        System.out.println(instance1 == instance2);//true 同一对象

        System.out.println("hashcode= "+instance1.hashCode()+"  "+instance2.hashCode());

    }
}
经验分享 程序员 微信小程序 职场和发展