zoukankan      html  css  js  c++  java
  • 单件模式(单例模式)

    单件模式,又称单例模式

    /**
     * 单例,版本一,此版本多线程下有问题。不要使用
     */
    public class Singleton00 {
        private Singleton00() {    }
        private static Singleton00 uniqueInstance;
        public static Singleton00 getInstance() {
            if(null == uniqueInstance) {
                uniqueInstance = new Singleton00();
            }
            return uniqueInstance;
        }
    }
    
    
    /**
     * 单例,版本2,加锁,同步这个方法,效率低
     */
    public class Singleton01 {
        private Singleton01() {    }
        private static Singleton01 uniqueInstance;
        public static synchronized Singleton01 getInstance() {
            if(null == uniqueInstance) {
                uniqueInstance = new Singleton01();
            }
            return uniqueInstance;
        }
    }
    
    /**
     * 单例,版本3,急切版,饿汉版,多线程下没有问题。
     * JVM在加载这个类时,马上就创建 uniqueInstance,保证了线程安全。thread safe。
     */
    public class Singleton02 {
        private Singleton02() {    }
        private static Singleton02 uniqueInstance = new Singleton02();
        public static Singleton02 getInstance() {
            return uniqueInstance;
        }
    }
    
    
    /**
     * 单例,版本4,双重检查加锁,double-checked locking。版本2的改进,效率高。
     */
    public class Singleton03 {
        private Singleton03() {    }
        //volatile 关键字确保:当uniqueInstance变量被初始化成实例时,多线程的uniqueInstance同时改变。
        private volatile static  Singleton03 uniqueInstance;
        public static Singleton03 getInstance() {
            if(null == uniqueInstance) {
                synchronized(Singleton03.class) {
                    if(null == uniqueInstance) {
                        uniqueInstance = new Singleton03();
                    }
                }
            }
            return uniqueInstance;
        }
    }

    常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。

    昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
  • 相关阅读:
    jsp mysql 配置线程池
    服务端 模拟 检测 攻击。。乱写
    硕思闪客精灵 7.2 破解版
    unity UnityAwe 插件
    smartfoxserver 2x 解决 Math NAN
    unity 断点下载
    java 监听文件目录修改
    wind7 64 setup appjs
    sfs2x 修改jvm 内存
    unity ngui 解决图层问题
  • 原文地址:https://www.cnblogs.com/htj10/p/14979075.html
Copyright © 2011-2022 走看看