线程安全单例模式
曾去腾讯公司面试,给这题卡了,他们要的是最优最优,好吧,来个最优饿汉式线程安全单例模式:
package com.esom.tech.pattern;
/**
* 线程安全单例模式
*/
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
/**
* 对象的创建线程安全,而不是对象的获取
* 故不对getInstance方法做线程同步
*/
synchronized (Singleton.class) {
// 加null比较判断,避免多个线程同步等待后获取不同实例
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
} 相关推荐
fraternityjava 2020-06-14
ahnuzfm 2020-05-07
gongruitao 2020-05-02
xiaoemo0 2020-04-08
付春杰Blog 2020-03-26
Hy 2020-11-13
xrslt 2020-11-06
yutian0 2020-10-26
杨树 2020-09-21
zhuyonge 2020-08-01
zhuyonge 2020-07-26
xiaoemo0 2020-07-18
fraternityjava 2020-06-26
luohui 2020-06-26
dxyadc 2020-06-26
luohui 2020-06-21
三动 2020-06-21
fengyun 2020-06-14