zoukankan      html  css  js  c++  java
  • 单利模式(饿汉模式,懒汉模式)线程安全与解决问题

    单例模式

    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 关键字

  • 相关阅读:
    推荐一个css抖动库
    八佰
    如何将猫猫监控放在博客上
    一个springboot注解不成功的小问题
    vue整理
    springboot整理
    国外服务器:org.xml.sax.SAXParseException
    记一次tomcat运行起来了但是项目没起来的问题
    一个狗血的mysql编码错误
    js中for(var key in o ){};用法小记
  • 原文地址:https://www.cnblogs.com/da-peng/p/8278714.html
Copyright © 2011-2022 走看看