1、原始的单利方式(多线程并发,会重复new对象,不推荐使用)
Android
public class MyInstance {
private static MyInstanceinstance;
public static MyInstance getInstance(){
if(instance==null){
instance=new MyInstance();
}
return instance;
}
}
kotlin
class MyInstance {
companion object{
val instance by lazy(LazyThreadSafetyMode.NONE){
MyInstance()
}
}
}
2、添加线程锁(实现了单例,但是效率降低了,不推荐使用)
Android
public class MyInstance {
private static MyInstance instance;
public static synchronized MyInstance getInstance(){
if(instance==null){
instance=new MyInstance();
}
return instance;
}
}
Kotlin
class MyInstance {
companion object{
private var instance:MyInstance?=null
@Synchronized
fun get():MyInstance{
if(null==instance)instance=MyInstance()
return instance as MyInstance
}
}
}
3、双层加锁判断,并且线程安全(推荐使用)
public class MyInstance {
private static MyInstance instance;
public static MyInstance getInstance() {
if (instance ==null) {
synchronized (MyInstance.class) {
if(instance==null){
instance=new MyInstance();
}
}
}
return instance;
}
}
Kotlin
class MyInstance {
companion object{
val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED){
MyInstance()
}
}
}