实现线程安全单例模式的两种方式:
1.双重检查+同步:
public class Singleton
{
private volatile static singletonInstance;
private Singleton(){}
public static Singleton getSingleton()
{
if(singletonInstance == NULL)
{
synchronized(Singleton.class)
{
singletonInstance = new singletonInstance();
}
}
return singletonInstance;
}
}
2.利用静态内部类只能初始化一次实现:
public class Singleton
{
private Singleton(){}
public static Singleton getSingletonInstance()
{
return Nested.singletoninstance;
}
////在第一次被引用时被加载,由于内部静态类只会被加载一次,故该实现方式时线程安全的
static class Nested
{
private static Singleton singletoninstance = new Singleton();
}
}