kotlin实现
}
java实现
public class LazyNotThreadSafe {
private static LazyNotThreadSafe INSTANCE;
private LazyNotThreadSafe(){}
public static LazyNotThreadSafe getInstance(){
if(INSTANCE == null){
INSTANCE = new LazyNotThreadSafe();
}
return INSTANCE;
}
}
java实现
public class LazyThreadSafeSynchronized {
private static LazyThreadSafeSynchronized INSTANCE;
private LazyThreadSafeSynchronized(){}
public static synchronized LazyThreadSafeSynchronized getInstance(){
if(INSTANCE == null){
INSTANCE = new LazyThreadSafeSynchronized();
return INSTANCE;
}
}
kotlin实现
class LazyThreadSafeSynchronized private constructor() {
companion object {
private var instance: LazyThreadSafeSynchronized? = null
@Synchronized
fun get(): LazyThreadSafeSynchronized{
if(instance == null) instance = LazyThreadSafeSynchronized()
return instance!!
}
}
}
kotlin实现
class LazyThreadSafeDoubleCheck private constructor(){
companion object{
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
LazyThreadSafeDoubleCheck()
}
private @Volatile var instance2: LazyThreadSafeDoubleCheck? = null
if(instance2 == null){
synchronized(this){
if(instance2 == null)
instance2 = LazyThreadSafeDoubleCheck()
}
}
return instance2!!
}
}
}
java实现
public class LazyThreadSafeStaticInnerClass {
private static class Holder{
private static LazyThreadSafeStaticInnerClass INSTANCE = new LazyThreadSafeStaticInnerClass();
}
private LazyThreadSafeStaticInnerClass(){}
public static LazyThreadSafeStaticInnerClass getInstance(){
return Holder.INSTANCE;
}