/ ** * lazy simple interest thread-safe mode * @author 15,735,400,536 * / public class the Singleton { / ** * instance of the object * / Private the Singleton static Singleton; / ** * constructor privatization, external objects can not be created * / the Singleton Private () { } / ** * Get example method * @return * / public static the Singleton the getInstance () { IF (Singleton == null) { Singleton the Singleton new new = (); } return Singleton; } }
solution:
/ ** * Example lazy single thread safe * @author 15,735,400,536 * * / public class IdlerSingleton { / ** * instance of the object * / Private static IdlerSingleton idlerSingleton; / ** * privatization constructor * / Private IdlerSingleton () { } / ** * plus synchronized keyword * @return * / public static synchronized idlerSingleton the getInstance () { IF (idlerSingleton == null) { idlerSingleton new new idlerSingleton = (); } return idlerSingleton; } // add sync block: / / public static IdlerSingleton getNewInstance () { / / if (null == idlerSingleton) { // synchronized (IdlerSingleton.class) { // idlerSingleton = new IdlerSingleton(); // } // } // return idlerSingleton; // } }
/ ** * single double-check mode insecurity in lazy interest simple interest occurs in multithreading solution * @author 15,735,400,536 * * / public class DoubleCheckSingleton { Private static volatile DoubleCheckSingleton doubleCheckSingleton; Private DoubleCheckSingleton () {} public static DoubleCheckSingleton the getInstance () { IF (doubleCheckSingleton == null) { the synchronized (DoubleCheckSingleton.class) { IF (doubleCheckSingleton == null) { doubleCheckSingleton new 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; } }
/ ** * starving simple interest thread safe * @author 15,735,400,536 * * / public class NewHungrySingleton { / ** * Constant static instance of the object * / Private Final static NewHungrySingleton newHungrySingleton new new NewHungrySingleton = (); Private NewHungrySingleton () {} / * * * when starving NewHungrySingleton class loader, it is an object instance has been created * @return * / public static NewHungrySingleton the getInstance () { return newHungrySingleton; } }