zoukankan      html  css  js  c++  java
  • 关于单例模式的想法-volatile

    今天看着一个多线程并发用到的关键字:volatile,看了不少资料发现这个是一个共享的直接写入内存使用的关键字修饰变量,用来修饰类变量或者类静态变量,所以有了一个关于单利模式的想法,我们都知道的单例模式的一个写法是:

    class Singleton{
        private static Singleton instance = null;
     
        private Singleton() {
     
        }
     
        public static Singleton getInstance() {
            if(instance==null) {
                synchronized (Singleton.class) {
                    if(instance==null)
                        instance = new Singleton();
                }
            }
            return instance;
        }
    }
    

      当然单例模式还有其他的写法,我要说的是将关键字volatile加在变量instance上:

    class Singleton{
        private volatile static Singleton instance = null;
     
        private Singleton() {
     
        }
     
        public static Singleton getInstance() {
            if(instance==null) {
                synchronized (Singleton.class) {
                    if(instance==null)
                        instance = new Singleton();
                }
            }
            return instance;
        }
    }
    

      因为用votalite修饰的变量,在修改时是直接将变量值写进物理内存中去的,不会写入缓存中去,这样,单例模式就更加的,,,,好了

  • 相关阅读:
    2019 Multi-University Training Contest 10
    自考新教材-p326_3(1)
    自考新教材-p322
    自考新教材-p321
    自考新教材-p316
    自考新教材-p315
    自考新教材-p313
    自考新教材-p311
    自考新教材-p310
    自考新教材-p309
  • 原文地址:https://www.cnblogs.com/milude0161/p/7490933.html
Copyright © 2011-2022 走看看