饿汉式:通过静态常量、静态代码块实现,线程同步
懒汉式:判断null之后再new对象,线程不同步
线程安全,延迟加载,效率高
仅当调用getInstance()方法时,静态内部类才进行加载,加载遵循双亲委派模式,加载过程线程安全
1 2 3 4 5 6 7 8 9 10 11 12public class Singleton { private Singleton() { } private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }
线程安全,延迟加载,效率高
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18public class Singleton { private static volatile Singleton singleton; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
Copyright ©2010-2022 比特日记 All Rights Reserved.