/** * 懒汉单利模式 线程不安全 * @author 15735400536 */ public class Singleton { /** * 实例对象 */ private static Singleton singleton; /** * 私有化构造函数,使外部不能创建对象 */ private Singleton() { } /** * 获取实例方法 * @return */ public static Singleton getInstance() { if(null == singleton) { singleton = new Singleton(); } return singleton; } }
解决方案:
/** * 懒汉单例 线程安全 * @author 15735400536 * */ public class IdlerSingleton { /** * 实例对象 */ private static IdlerSingleton idlerSingleton; /** * 私有化构造函数 */ private IdlerSingleton() { } /** * 加了synchronized关键字 * @return */ public static synchronized IdlerSingleton getInstance() { if(null == idlerSingleton) { idlerSingleton = new IdlerSingleton(); } return idlerSingleton; } //或者添加同步代码块: // public static IdlerSingleton getNewInstance() { // if(null == idlerSingleton) { // synchronized (IdlerSingleton.class) { // idlerSingleton = new IdlerSingleton(); // } // } // return idlerSingleton; // } }
/** * 双重检查单利模式 解决懒汉单利在多线程情况下发生不安全问题解决方案 * @author 15735400536 * */ public class DoubleCheckSingleton { //volatile 禁止重排序 private static volatile DoubleCheckSingleton doubleCheckSingleton; private DoubleCheckSingleton() {} public static DoubleCheckSingleton getInstance() { if(null == doubleCheckSingleton) { synchronized (DoubleCheckSingleton.class) { if(null == doubleCheckSingleton) { doubleCheckSingleton = new DoubleCheckSingleton(); } } } return doubleCheckSingleton; } }
/** * 饿汉单例 线程安全 * @author 15735400536 * */ public class HungrySingleton { /** * 静态代码块 */ static { hungrySingleton = new HungrySingleton(); } private static HungrySingleton hungrySingleton; private HungrySingleton() {} public static HungrySingleton getInstance() { return hungrySingleton; } }
/** * 饿汉单利 线程安全 * @author 15735400536 * */ public class NewHungrySingleton { /** * 静态常量实例对象 */ private final static NewHungrySingleton newHungrySingleton = new NewHungrySingleton(); private NewHungrySingleton() {} /** * 饿汉 NewHungrySingleton类加载时,实例对象就已经创建好了 * @return */ public static NewHungrySingleton getInstance() { return newHungrySingleton; } }