饿汉式
/*静态常量饿汉式*/public class HungryStaticCode {private final static HungryStaticCode hungryStaticCode = new HungryStaticCode();private HungryStaticCode() {}public static HungryStaticCode getInstance() {return hungryStaticCode;}}/*静态块饿汉式*/public class SingletonBlock {private static SingletonBlock singletonBlock;static {singletonBlock = new SingletonBlock();}public static SingletonBlock getInstance() {return singletonBlock;}}//类装载时就完成了实例化,可能会造成内存浪费
懒汉式
/*线程不安全懒汉式*/public class LazyNoSafe {private static LazyNoSafe lazyNoSafe;private LazyNoSafe() {}public static LazyNoSafe getInstance() {if (lazyNoSafe == null) {lazyNoSafe = new LazyNoSafe();}return lazyNoSafe;}}/*线程安全懒汉式*/public class LazySafe {private static LazySafe lazyNoSafe;private LazySafe() {}public static synchronized LazySafe getInstance() {if (lazyNoSafe == null) {lazyNoSafe = new LazySafe();}return lazyNoSafe;}}/*同步代码块懒汉式-----不可使用*/public class LazyBlock {private static LazyBlock lazyBlock;private LazyBlock() {}public static LazyBlock getInstance() {if (lazyBlock == null) {synchronized (LazyBlock.class) {lazyBlock = new LazyBlock();}}return lazyBlock;}}
双重检测模式
public class DoubleSafe {private static DoubleSafe doubleSafe;private DoubleSafe () {}public static DoubleSafe getInstance() {if (doubleSafe == null) {synchronized (DoubleSafe.class) {if (doubleSafe == null) {doubleSafe = new DoubleSafe();}}}return doubleSafe;}}
静态内部类延迟加载(推荐使用)
懒加载+类第一次加载才会初始化,在初始化的时候别的线程无法进入,保证了线程安全
public class StaticInside {private static volatile StaticInside staticInside;private StaticInside() {}private static class StaticInsideInstance {private static final StaticInside STATIC = new StaticInside();}public static synchronized StaticInside getInstance() {return StaticInsideInstance.STATIC;}}
