单例模式

  1. 懒汉式:线程是不安全的,若多个线程同时进入if(uniqueInstance==null)
    public class Singleton {
        private static Singleton uniqueInstance;
        private Singleton() {
        }
        public static Singleton getUniqueInstance() {
            if (uniqueInstance == null) {
                uniqueInstance = new Singleton();
            }
            return uniqueInstance;
        }
    }
  2. 懒汉式线程安全:一个线程进入方法后,其他试图进入的线程必须等待,性能有损耗
    public static synchronized Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
  3. 双重校验锁:先判断是否已经实例化,如果没有才对实例化语句加锁,内部是if(==null)是为了防止两个线程同时进入外层的if语句块内

    public class Singleton {
        private volatile static Singleton uniqueInstance;
        private Singleton() {
        }
        public static Singleton getUniqueInstance() {
            if (uniqueInstance == null) {
                synchronized (Singleton.class) {
                    if (uniqueInstance == null) {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
    }
原文地址:https://www.cnblogs.com/kangaroohu/p/9604779.html