线程安全单例的三种实现方式
1、饿汉式(未实现懒加载)
public class singleton{
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}
2、懒汉式(实现懒加载)
public class singleton{
private static Singleton singleton;
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
3、静态内部类(实现懒加载)
public class Singleton{
private Singleton(){}
private static class Inner(){
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return Inner.singleton;
}
}