class Singleton {
private static Singleton sInstance = new Singleton();
//私有构造方法
private Singleton() {
}
public static Singleton getInstance() {
return sInstance;
}
}
class Singleton {
private static Singleton sInstance;
//私有构造方法
private Singleton() {
}
public static Singleton getInstance() {
if (sInstance == null) {
//多个线程进入判断会创建不同的实例
sInstance = new Singleton();
}
return sInstance;
}
}
class Singleton {
private static Singleton sInstance;
//私有构造方法
private Singleton() {
}
//使用 synchronized 保证互斥
public static synchronized Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
}
}
class Singleton {
private static volatile Singleton sInstance;
// 私有构造方法
private Singleton() {
}
public static Singleton getInstance() {
if (sInstance == null) {
//如果多个线程进入判断,通过加锁保证互斥
synchronized (Singleton.class) {
if (sInstance == null) {
sInstance = new Singleton();
}
}
}
return sInstance;
}
}
class Singleton {
// 私有构造方法
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}