多线程环境单例模式 : 双重检测+上锁
public class Singleton {
/**
* 结构器私有化避免被公共创立
*/
private Singleton() {
}
//创立多线程锁
private static Object lock = new Object();
//单例本体
private static Singleton singleton = null;
//获取单例
public static Singleton getInstance() {
//当多线程环境中单例本体为空
if (singleton == null) {
//上锁避免被其余线程争夺
synchronized (lock) {
//双重查看更加平安和合乎业务场景
if (singleton == null) {
//加锁和双重检测后初始化单例
singleton = new Singleton();
}
}
}
//返回单例后果
return singleton;
}
}
发表回复