1. 双层检查
public class SingletonDemo1 {
private static SingletonDemo1 instance;
private SingletonDemo1() {
}
public static SingletonDemo1 getInstance() {
if (null == instance) {
synchronized (SingletonDemo1.class) {
if (null == instance) {
instance = new SingletonDemo1();
}
}
}
return instance;
}
}
2. 内部类Holder
public class SingletonDemo2 {
private SingletonDemo2() {
}
private static class InstanceHolder {
private final static SingletonDemo2 instance = new SingletonDemo2();
}
public static SingletonDemo2 getInstance() {
return InstanceHolder.instance;
}
}
3. 使用enum作为单例
public class SingletonDemo3 {
private SingletonDemo3() {
}
private enum Instance {
INSTANCE;
private final SingletonDemo3 instance;
Instance() {
instance = new SingletonDemo3();
}
public SingletonDemo3 getInstance() {
return instance;
}
}
public static SingletonDemo3 getInstance() {
return Instance.INSTANCE.getInstance();
}
public static void main(String[] args) {
IntStream.range(0, 100).forEach((item) -> {
Thread thread = new Thread(() -> {
System.out.println(SingletonDemo3.getInstance());
});
thread.start();
});
}
}