第一种:
private static Singleton _instance; public static synchronized Singleton getInstance() { if (_instance == null) { _instance = new Singleton(); } return _instance; }
在静态方法上加 synchronized,等同于将整个类锁住。每当 new 该对象时,就需要同步:
if (_instance == null) { _instance = new Singleton(); }
第二种:
public class Singleton { //volatile 防止延迟初始化 private volatile static Singleton instance; public static Singleton getInstance() { if (instance == null) { //判断是否已有单例生成 synchronized (Singleton.class) { if (instance == null) //判断是否已经赋值 instance = new Instance();//instance为volatile,现在没问题了 } } return instance; } }
判断是否有单例生成并不需要同步锁,只有在第一次单例类实例创建时需要同步锁。但在同步锁中赋值时,还需再检验一次。