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

懒汉式( 线程不安全)
优缺点说明:
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());

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值