Java常用设计模式之单列模式的创建

单列模式就是这个类只允许有一个对象,单列模式又分懒汉式和饿汉式,下面我们通过代码来看看懒汉式和饿汉式的区别:

1.懒汉式

public class SingletonLazy {

    // volatile:将singleton设置为可见性(每个线程都只能从主内存获取singleton)
    private static volatile SingletonLazy singletonLazy = null;

    private SingletonLazy() {}

    /**
     * 方法用途: 获取对象<br/>
     * 操作步骤: TODO<br/>
     * ${tags}
     */
    public static SingletonLazy getInstance() {
        // singleton是可见的,如果有线程已经创建了singleton对象,这里不为null,直接返回singleton对象
        if (null == singletonLazy) {
            // 加上synchronized同步锁,只能有一个线程访问
            synchronized (SingletonLazy.class) {
                // 二次判断singleton对象是否还没有被创建
                if (null == singletonLazy) {
                    singletonLazy = new SingletonLazy();
                }
            }
        }
        return singletonLazy;
    }

}

这里我们为什么要加synchronized呢?

因为懒汉式他是线程不安全的;singletonLazy 初始化是null,如果多个线程同时获取singletonLazy对象,每个线程都会去new一个SingletonLazy,这样就变成了多例了;所以我们在singletonLazy = new SingletonLazy()这段代码加上synchronized,二次判断singletonLazy是否为空,这样就解决了多线程并发访问线程安全的问题。

2.饿汉式:

public class SingletonHunger {

    private static SingletonHunger singletonHunger = new SingletonHunger();

    private SingletonHunger() {}

    public static SingletonHunger getInstance() {
        return singletonHunger;
    }

}

因为饿汉式在程序启动的时候就创建singletonHunger对象,所以不存在线程安全问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值