单例模式

double check lock 懒汉模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DCLSingleton {
// 使用 volatile 关键字,防止指令重排
private static volatile DCLSingleton instance;

private DCLSingleton() {
System.out.println("DCLSingleton 被实例化");
}

public static DCLSingleton getInstance() {
// 第一次检查:如果实例已存在,直接返回
if (instance == null) {
// 加锁
synchronized (DCLSingleton.class) {
// 第二次检查:防止多个线程同时进入第一个 if 后重复创建实例
if (instance == null) {
instance = new DCLSingleton();
}
}
}
return instance;
}
}

饿汉模式

1
2
3
4
5
6
7
8
9
10
11
12
public class EagerSingleton {
// 在类加载时就初始化实例
private static final EagerSingleton INSTANCE = new EagerSingleton();

private EagerSingleton() {
System.out.println("EagerSingleton 被实例化");
}

public static EagerSingleton getInstance() {
return INSTANCE;
}
}

enum

1
2
3
4
5
6
7
8
9
10
11
public enum EnumSingleton {
INSTANCE;

EnumSingleton() {
System.out.println("EnumSingleton 被实例化");
}

public void doSomething() {
System.out.println("枚举单例执行方法");
}
}
文章目录
  1. 1. double check lock 懒汉模式
  2. 2. 饿汉模式
  3. 3. enum
| 本站总访问量次 ,本文总阅读量