我正在尝试找出以下 MC 问题的答案。我曾尝试在谷歌上寻找答案,但人们似乎对这个问题有不同的答案。有人可以解释他们的答案吗?
public class Gingleton {
private static Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
return INSTANCE;
}
private Gingleton() {
}
}
可以创建多个 Gingleton 实例(我的选择)
永远不会创建 Gingleton
构造函数是私有(private)的,不能调用
值可以被垃圾回收,调用 getInstance 可能 返回垃圾数据
最佳答案
getInstance()
中的新实例创建不是以任何方式同步的,因此在多线程环境中可能会创建多个实例。为确保只有一个实例,您应该执行以下操作:
public class Gingleton {
// volatile
private static volatile Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
synchronized (Gingleton.class) { // Synchronized
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
}
}
return INSTANCE;
}
private Gingleton() {
}
}
关于java - 私有(private)构造函数和实例 - 多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22282333/