JAVA单例模式

/**
 * 单例模式-饿汉模式
 *
 * @author Austinson
 * 该类加载的时候会直接new一个对象出来,当这样的类比较多时就会使得启动的速度变慢,适合小系统。
 *
 */
public class SingletonByHungry {

    private static SingletonByHungry singletonByHungry = new SingletonByHungry();//初始化实例对象

    private SingletonByHungry() {//构建函数私有化,保证其他对象不能直接new一个此对象的实例
    };

    public static SingletonByHungry getSingletonByHungry() {
        return singletonByHungry;
    }

}

/**
 * 单例模式-懒汉模式
 *
 * @author Austinson
 *
 */
public class SingletonByLazy {

    // private static SingletonByLazy singletonByLazy = null;
    //
    // private SingletonByLazy() {
    // };
    //
    // /**
    // * 加synchronized关键字不会出现线程安全问题,但是会影响运行效率。
    // * @return
    // */
    // public static synchronized SingletonByLazy getSingletonByLazy() {
    // if (null == singletonByLazy) {
    // singletonByLazy = new SingletonByLazy();
    // }
    // return singletonByLazy;
    // }

    /** 双重校验 **/
    // 定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
    private volatile static SingletonByLazy singletonByLazy = null;

    private SingletonByLazy() {
    };

    // 使用同步做二次校验,保证实例对象不被重复实例化,保证线程间的安全,也保证高效性
    public static SingletonByLazy getSingletonByLazy() {
        if (null == singletonByLazy) {
            // 二次校验
            synchronized (SingletonByLazy.class) {
                if (null == singletonByLazy) {
                    singletonByLazy = new SingletonByLazy();
                }
            }
        }
        return singletonByLazy;
    }

}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值