一、线程不安全的单例模式
public class SingleTon{
private static SingleTon INSTANCE = null;
private SingleTon(){}
public static SingleTon getInstance(){
if(INSTANCE == null){
INSTANCE = new SingleTon();
}
return instance;
}
}
二、线程安全且高效的单例模式
1.双重校验锁
public class SingleTon{
volatile private static SingleTon INSTANCE = null;
private SingleTon(){}
public static SingleTon getInstance(){
if(INSTANCE == null){
synchronized(SingleTon.class){
if(INSTANCE == null){
INSTANCE = new SingleTon();
}
}
}
return instance;
}
}
2.静态内部类
public class SingleTon{
private SingleTon(){}
private static class Holder{
private static SingleTon INSTANCE = new SingleTon();
}
public static SingleTon getInstance(){
return Holder.INSTANCE;
}
}