线程安全的单例模式
程序员文章站
2022-07-14 09:17:29
...
实现线程安全单例模式的两种方式:
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();
}
}