• 单利模式(饿汉模式,懒汉模式)线程安全与解决问题


    单例模式

    1.饿汉模式:在类被加载的时候创建实例(线程安全的)

    2.懒汉模式:在方法被运行的时候创建实例(线程不安全的) 解决方法:通过双检验

    饿汉模式:

    public class Singleton {
        //饿汉模式
        //将构造函数私有化
        private Singleton(){
    
        }
        //将对象实例化
        private static Singleton instance = new Singleton();
    
        //得到实例的方法
    
        public static Singleton getInstance() {
            return instance;
        }
    }

    懒汉模式:

    //懒汉模式
        //将构造函数私有化
        private Singleton(){
    
        }
        //将对象实例化
        private static Singleton instance ;
    
        //得到实例的方法
    
        public static Singleton getInstance() {
           if(instance == null){
               instance = new Singleton();
           }
            return instance;
        }

    解决方法1(慢)

    //得到实例的方法
    
        synchronized public static Singleton getInstance() {
           if(instance == null){
               instance = new Singleton();
           }
            return instance;
        }

    解决方法2(慢)

     //得到实例的方法
    
         public static Singleton getInstance() {
          synchronized (Singleton.class){
              if(instance == null){
                  instance = new Singleton();
              }
              return instance;
          }
        }

    解决方法3(推荐)

    原因:如果实例已经存在,就不存在线程安全的问题,可以直接获取实例,减少了加锁而造成的速度问题。

    public class Singleton {
        //懒汉模式
        //将构造函数私有化
        private Singleton(){
    
        }
        //将对象实例化
        private static volatile  Singleton instance ;
    
        //得到实例的方法
    
         public static Singleton getInstance() {
             if(instance == null) {
                 synchronized (Singleton.class) {
                     if (instance == null) {
                         instance = new Singleton();
                     }
                 }
             }
             return instance;
        }
    }

    volatile 关键字

  • 相关阅读:
    《解密腾讯海量服务之道》讲座笔记
    图解 Paxos 一致性协议
    向量时钟算法简介——本质类似MVCC
    logback配置
    Protocol Buffers简明教程
    分布式调用技术 RPC VS REST
    Dubbo和Spring Cloud微服务架构对比
    Spring Boot学习笔记
    relatedTarget、fromElement、toElement相关元素
    12个不可不知的Sublime Text应用技巧和诀窍
  • 原文地址:https://www.cnblogs.com/da-peng/p/8278714.html
Copyright © 2020-2023  润新知