曾去腾讯公司面试,给这题卡了,他们要的是最优最优,好吧,来个最优饿汉式线程安全单例模式:
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; } }