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

  • 相关阅读:
    day14(xml 编写及解析)
    day11(多线程,唤醒机制,生产消费者模式,多线程的生命周期)
    day13(反射,BeanUtils包)
    day10(IO流汇总)
    day08(File类 ,字节流)
    day08(异常处理,创建异常,finally,throws和throw的区别)
    [SPOJ-PT07J] Query on tree III (主席树)
    [ZJOI2008] 树的统计(树链剖分)
    长链剖分学习笔记
    [BZOJ4260] Codechef REBXOR (01字典树,异或前缀和)
  • 原文地址:https://www.cnblogs.com/da-peng/p/8278714.html
Copyright © 2011-2022 走看看