我正在尝试找出以下 MC 问题的答案。我尝试在谷歌上寻找答案,但人们似乎对这个问题有不同的答案。有人可以解释一下他们的答案吗?
public class Gingleton {
private static Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
return INSTANCE;
}
private Gingleton() {
}
}
Run Code Online (Sandbox Code Playgroud)
可以创建多个 Gingleton 实例(我的选择)
Gingleton 永远不会被创建
构造函数是私有的,不能被调用
value 可以被垃圾回收,调用 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() {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |