volatile变量双重判空
class Singleton{
private Singleton(){}
private volatile static Singleton instance;
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
静态内部类
public class Singleton{
private Singleton(){}//私有构造方法,避免外部创建实例
private static class SingletonHolder
{
public static Singleton instance= new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.instance;
}
}
网友评论