1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 双检锁方式
public class Singleton {

private static Singleton instance = null;

private Singleton() {
}

public static Singleton getInstance() {
if (instance == null) { // 优化 synchronized 同步化方法效率
synchronized (Singleton.class) { // 保证下面线程安全
if (instance == null) {
instance = new Singleton(); // 多线程可实例化多次
}
}
}
return instance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 静态内部类方式:
public class Singleton {

private static class SingletonHolder {
public static Singleton instance = new Singleton();
}

private Singleton() {
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}
}