You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
723 B
32 lines
723 B
### 1.内部静态类
|
|
内部静态类即使存在多个类加载器的情况下也只会初始化一次,因此是线程安全的
|
|
```java
|
|
public class StaticHolderSingleton {
|
|
|
|
private StaticHolderSingleton() {
|
|
}
|
|
|
|
private static class ClassHolder {
|
|
static final StaticHolderSingleton INSTANCE = new StaticHolderSingleton();
|
|
}
|
|
|
|
public static StaticHolderSingleton getInstance() {
|
|
return ClassHolder.INSTANCE;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
StaticHolderSingleton clz = StaticHolderSingleton.getInstance();
|
|
}
|
|
}
|
|
```
|
|
### 2.基于枚举
|
|
```java
|
|
public enum EnumSingleton {
|
|
INSTANCE;
|
|
|
|
EnumSingleton() {
|
|
|
|
}
|
|
}
|
|
```
|
|
当EnumSingleton.INSTANCE首次被引用时才会被初始化 |