14.线程安全的懒汉模式(单例设计模式)

将单例设计模式的懒汉模式改为线程安全的

同时回顾单例设计模式的两种模式的特点及其代码书写模板
回顾多线程的实现方式以及实现多线程同步的方式

package com.senior.multithread;

/**
 * @author eden
 * @create projectTest:2021-05-10-21:36
 */
public class SingletonSecurity {
    public static void main(String[] args) {
        
    }
}


//单例模式:只允许创建一个该类对象
//单例设计模式饿汉模式-->线程安全
class SingletonHungry {
    public SingletonHungry() {
    }

    public static SingletonHungry singletonHungry = new SingletonHungry();

    public static SingletonHungry getSingletonHungry() {
        return singletonHungry;
    }

}

//单例设计模式懒汉模式
class SingletonLazy {
    public SingletonLazy() {
    }

    public static SingletonLazy singletonLazy;

    //实现同步的方式一:直接将其声明为一个同步方法
//    public static synchronized SingletonLazy getSingletonLazy(){
//        ....
//    }
    public static SingletonLazy getSingletonLazy() {
        //方式二:同步代码块,效率略差
        //分析:假设现在有n个线程,线程1进来之后,加锁运行,创建了一个对象singletonLazy
        //此时singletonLazy非空,线程2进来之后实际上什么都没做就出去了,之后的所有进程
        //都一样。这样一来效率很差,实际上后面的进程根本不需要进方法体内。改进:方式三
//        synchronized(SingletonLazy.class){
//            if(singletonLazy == null)
//            {
//                singletonLazy = new SingletonLazy();
//            }
//            return singletonLazy;
//        }
        //方式三:改进方式一
        if (singletonLazy == null) {
            synchronized (SingletonLazy.class) {
                if (singletonLazy == null) {
                    singletonLazy = new SingletonLazy();
                }
            }
        }
        return singletonLazy;


    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值