前言:直接介紹幾種線程安全的且我覺得還比較不錯的方式:
1.
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton getInstance()
{
return instance ;
}
}
2、懶漢
public class Singleton02
{
private static Singleton02 instance;
public static Singleton02 getInstance()
{
if (instance == null)
{
synchronized (Singleton02.class)
{
if (instance == null)
{
instance = new Singleton02();
}
}
}
return instance;
}
}
3、使用一個持有類,主要是爲了不在初始化的時候加載
public class Singleton04
{
private static final class InstanceHolder
{
private static Singleton04 INSTANCE = new Singleton04();
}
public static Singleton04 getInstance()
{
return InstanceHolder.INSTANCE;
}
}