kotlin实现

  1. }

java实现

  1. public class LazyNotThreadSafe {
  2. private static LazyNotThreadSafe INSTANCE;
  3. private LazyNotThreadSafe(){}
  4. public static LazyNotThreadSafe getInstance(){
  5. if(INSTANCE == null){
  6. INSTANCE = new LazyNotThreadSafe();
  7. }
  8. return INSTANCE;
  9. }
  10. }

java实现

  1. public class LazyThreadSafeSynchronized {
  2. private static LazyThreadSafeSynchronized INSTANCE;
  3. private LazyThreadSafeSynchronized(){}
  4. public static synchronized LazyThreadSafeSynchronized getInstance(){
  5. if(INSTANCE == null){
  6. INSTANCE = new LazyThreadSafeSynchronized();
  7. return INSTANCE;
  8. }
  9. }

kotlin实现

  1. class LazyThreadSafeSynchronized private constructor() {
  2. companion object {
  3. private var instance: LazyThreadSafeSynchronized? = null
  4. @Synchronized
  5. fun get(): LazyThreadSafeSynchronized{
  6. if(instance == null) instance = LazyThreadSafeSynchronized()
  7. return instance!!
  8. }
  9. }
  10. }

kotlin实现

  1. class LazyThreadSafeDoubleCheck private constructor(){
  2. companion object{
  3. val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
  4. LazyThreadSafeDoubleCheck()
  5. }
  6. private @Volatile var instance2: LazyThreadSafeDoubleCheck? = null
  7. if(instance2 == null){
  8. synchronized(this){
  9. if(instance2 == null)
  10. instance2 = LazyThreadSafeDoubleCheck()
  11. }
  12. }
  13. return instance2!!
  14. }
  15. }
  16. }

java实现

  1. public class LazyThreadSafeStaticInnerClass {
  2. private static class Holder{
  3. private static LazyThreadSafeStaticInnerClass INSTANCE = new LazyThreadSafeStaticInnerClass();
  4. }
  5. private LazyThreadSafeStaticInnerClass(){}
  6. public static LazyThreadSafeStaticInnerClass getInstance(){
  7. return Holder.INSTANCE;
  8. }