标签:ack obj nal sync png bubuko 分享图片 img final
代码注释有介绍
package singleton; /** * @author: ycz * @date: 2018/12/24 0024 22:15 * @description: 懒汉模式 */ public class SingleTon1 { public SingleTon1(){} private static SingleTon1 instance1 = null; public static SingleTon1 getInstance1(){ if (instance1==null){ instance1 = new SingleTon1(); } return instance1; } }
package singleton; /** * @author: ycz * @date: 2018/12/24 0024 22:21 * @description: 饿汉模式 */ public class SingleTon2 { private SingleTon2(){} private static final SingleTon2 instance2 = new SingleTon2(); public static SingleTon2 getInstance2(){ return instance2; } }
package singleton; /** * @author: ycz * @date: 2018/12/24 0024 22:32 * @description: 解决多线程问题(在创建单例时加锁) */ public class SingleTon3 { private SingleTon3(){} private static SingleTon3 instance3 = null; public static synchronized SingleTon3 getInstance3(){ if (instance3 == null){ instance3 = new SingleTon3(); } return instance3; } }
package singleton; /** * @author: ycz * @date: 2018/12/24 0024 22:36 * @description: 在方法上加锁效率低下;可以先判断是否有创建过单例,如果没有在加锁创建 */ public class SingleTon4 { private SingleTon4(){} private static final Object myLocker = new Object(); private static SingleTon4 instance4 = null; public static SingleTon4 getInstance4(){ if (instance4 == null){ synchronized (myLocker){ instance4 = new SingleTon4(); } } return instance4; } }
这是SingleTon1(饿汉式)时会出现的问题。
标签:ack obj nal sync png bubuko 分享图片 img final
原文地址:https://www.cnblogs.com/hyczzz/p/10171472.html