Lazyman 懒汉模式 线程不安全
private static Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
Lazyman 懒汉模式 线程安全
private static Singleton2 instance;
private Singleton2() {
}
public static synchronized Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
饿汉模式
基于classloder机制避免了多线程的同步问题
private static Singleton3 instance = new Singleton3();
private Singleton3() {
}
public static Singleton3 getInstance() {
return instance;
}
饿汉模式2
private static Singleton4 instance;
static {
instance = new Singleton4();
}
private Singleton4() {
}
public static Singleton4 getInstance() {
return instance;
}
静态内部类
利用了classloder的机制来保证初始化instance时只有一个线程
Singleton类被装载了,instance不一定被初始化
只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类
private static class Singleton5Holder {
private static final Singleton5 INSTANCE = new Singleton5();
}
private Singleton5() {
}
public static final Singleton5 getInstance() {
return Singleton5Holder.INSTANCE;
}
枚举
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
双重校验锁
private volatile static Singleton7 instance;
private Singleton7() {
}
public static Singleton7 getInstance() {
if (instance == null) {
synchronized (Singleton7.class) {
if (instance == null) {
instance = new Singleton7();
}
}
}
return instance;
}