1.懒汉式-线程不安全
public class SingletonLazyNoSafe { private static SingletonLazyNoSafe singletonLazyNoSafe; private SingletonLazyNoSafe() {} public static SingletonLazyNoSafe getInstance(){ if (singletonLazyNoSafe ==null){ singletonLazyNoSafe = new SingletonLazyNoSafe(); } return singletonLazyNoSafe; } }
2.懒汉式-线程安全
public class SingletonLazySafe { private static SingletonLazySafe singletonLazySafe; private SingletonLazySafe(){ } public synchronized static SingletonLazySafe getInstance(){ if (singletonLazySafe == null){ singletonLazySafe = new SingletonLazySafe(); } return singletonLazySafe; } }
3.饿汉式-线程安全
public class SingletonHungerSafe { private static SingletonHungerSafe singletonHungerSafe = new SingletonHungerSafe(); private SingletonHungerSafe(){} public static SingletonHungerSafe getInstance(){ return singletonHungerSafe; } }
4.饿汉式-静态代码块-线程安全
public class SingletonHungerStaticBlockSafe { private static SingletonHungerStaticBlockSafe singletonHungerStaticBlockSafe; static { singletonHungerStaticBlockSafe = new SingletonHungerStaticBlockSafe(); } private SingletonHungerStaticBlockSafe(){} public static SingletonHungerStaticBlockSafe getInstance(){ return singletonHungerStaticBlockSafe; } }
5.懒汉式-静态内部类-线程安全
public class SingletonStaticInnerClass { private SingletonStaticInnerClass(){} private static class InstanceSingleton{ public static final SingletonStaticInnerClass SINGLETON_STATIC_INNER_CLASS = new SingletonStaticInnerClass(); } public static SingletonStaticInnerClass getInstance(){ return InstanceSingleton.SINGLETON_STATIC_INNER_CLASS; } }
6.懒汉式-双重校验锁-线程安全
public class SingletonDoubleVerifyLock { private static SingletonDoubleVerifyLock singletonDoubleVerifyLock; private SingletonDoubleVerifyLock(){} public static SingletonDoubleVerifyLock getInstance(){ if (singletonDoubleVerifyLock == null){ synchronized (SingletonDoubleVerifyLock.class){ if (singletonDoubleVerifyLock == null){ singletonDoubleVerifyLock = new SingletonDoubleVerifyLock(); } } } return singletonDoubleVerifyLock; } }
7.懒汉式-枚举实现-线程安全(推荐)
public enum SingletonEnum { INSTANCE; SingletonEnum() {} }
作者:李帅超
链接:https://www.jianshu.com/p/ea1ad96255b7
新
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦