- 懒汉模式的优化(synchronize解决线程安全问题)
package design_mode; public class SingletonSynchronized { private static SingletonSynchronized singletonSynchronized = null; private SingletonSynchronized(){ System.out.println("线程安全的单例模式"); } public static SingletonSynchronized getSingletonSynchronized(){ synchronized (SingletonSynchronized.class){ if ((singletonSynchronized == null)){ singletonSynchronized = new SingletonSynchronized(); } return singletonSynchronized; } } }
- 双重锁认证进一步提高性能
package design_mode; public class SingletonHight { private static SingletonHight singletonHight = null; private SingletonHight(){ System.out.println("最终版单例模式"); } public static SingletonHight getSingletonHight(){ if(singletonHight==null){ synchronized (SingletonHight.class){ if(singletonHight==null){ singletonHight = new SingletonHight(); } } } return singletonHight; } }
- 通过静态内部类实现单例模式的延迟加载和线程安全
public class SingletonInnerObject { private SingletonInnerObject(){}; private static class InnerObject { private static SingletonInnerObject singletonInnerObject = new SingletonInnerObject(); } public static SingletonInnerObject getInstance(){ return InnerObject.singletonInnerObject; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)