1 个回答

单例里加锁了么……

没加锁就会出现你这种问题。

按你这个逻辑大概写一个伪代码:

class Singleton {
  private static Singleton instance;

  public static Singleton getInstance()
    if (instance == null) {
      synchronized (LOCKSOMETHING) { // 要有锁
        if (instance == null) {
          Singleton temp = new Singleton();
          // do something to init...
          // 注意这里不要直接给 instance 赋值
          // 因为按你的逻辑,实例化后不等于初始化结束
          // 如果你直接赋值,可能会导致另一个线程判断 instance == null 不成立,从而认为初始化已结束
          // 所以这里要等你真正初始化结束后再给 instance 赋值
          instance = temp;
        }
      } 
    }

    return instance;
  }
}
推荐问题