线程安全的单例的几种实现方法
1. 使用synchronized
1.1 饱汉:双重检查锁定(double-checked locking)
public class SingleTon {
// 静态实例变量加上volatile
private static volatile SingleTon instance;
// 私有化构造函数
private SingleTon() {}
// 双重检查锁
public static SingleTon getInstance() {
if (instance == null) {
synchronized(SingleTon.class){
if(instance == null){
instance = new SingleTon();
}
}
}
return instance;
}1.2 饿汉
1.3 静态内部类
1.4 枚举
2. 利用CAS原理
3. 使用ThreadLocal
序列化与反序列化破坏单例问题
参考链接:
最后更新于