一、饿汉式-线程安全
线程安全,但无法实现实例懒加载策略
- /**
- * 饿汉式
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton {
- private static final Singleton singleton = new Singleton();
-
- private Singleton() {
- }
-
- public static Singleton getSingleton() {
- return singleton;
- }
- }
二、懒汉式-线程不安全
线程不安全,实现了实例懒加载策略。
- /**
- * 懒汉式
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton2 {
- private static Singleton2 singleton = null;
-
- private Singleton2() {
- }
-
- public static Singleton2 getSingleton() {
- if (singleton == null) {
- singleton = new Singleton2();
- }
- return singleton;
- }
- }
三、全局锁式-线程安全
线程安全,实现了懒加载策略,但是线程同步效率不高。
- /**
- * 全局锁
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton3 {
- private static Singleton3 singleton;
-
- private Singleton3() {
- }
-
- public synchronized static Singleton3 getSingleton() {
- if (singleton == null) {
- singleton = new Singleton3();
- }
- return singleton;
- }
- }
四、静态代码块式-线程安全
线程安全,类加载时初始化实例,实现了懒加载策略,线程安全。
- /**
- * 静态代码块
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton4 {
- private final static Singleton4 singleton;
-
- private Singleton4() {
- }
-
- static {
- singleton = new Singleton4();
- }
-
- public static Singleton4 getSingleton() {
- return singleton;
- }
- }
五、双重校验锁式-线程安全
线程安全,且实现了懒加载策略,同时保证了线程同步时的效率。
- /**
- * 双重校验锁
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton5 {
- private static Singleton5 singleton;
-
- private Singleton5() {
-
- }
-
- public static Singleton5 getSingleton() {
- if (singleton == null) {
- synchronized (Singleton5.class) {
- if (singleton == null) {
- singleton = new Singleton5();
- }
- }
- }
- return singleton;
- }
- }
六、内部类-线程安全
线程安全(类加载过程本就线程安全),不存在线程同步问题,单例对象在程序第一次调用getInstance()时主动加载 SingletonHolder和其 静态成员INSTANCE,因而实现了懒加载策略。推荐使用。
- /**
- * 内部类
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton6 {
- private Singleton6() {
- }
-
- private static class Singleton6Holder {
- private static final Singleton6 INSTANCE = new Singleton6();
- }
-
- public static Singleton6 getSingleton() {
- return Singleton6Holder.INSTANCE ;
- }
- }
七、枚举类-线程安全
线程安全,不存在线程同步问题,且单例对象在枚举类型 INSTANCE第一次引用时通过枚举的 构造函数初始化,从而实现了懒加载策略。推荐使用。
- /**
- * 枚举类
- * @author CC
- * @version 1.0
- * @since2023/10/12
- */
- public class Singleton7 {
- private Singleton7() {
- }
-
- enum SingletonEnum {
- INSTANCE;
-
- private final Singleton7 singleton;
-
- private SingletonEnum() {
- singleton = new Singleton7();
- }
- }
-
- public static Singleton7 getSingleton() {
- return SingletonEnum.INSTANCE.singleton;
- }
- }