以下是单例模式的双重检查实现。线程 A 正在执行 test=new Test();
行,但与此同时,线程 B 首先检查 test
的值。对于线程 B 来说,test
的值是多少?
class Test {
private Test test;
private Test() {
}
public static Test get() {
if (test == null) { // Thread B. When object is being created,
// what's value of test. Is it always null before
// Thread B new object?
synchronized (test.getClass()) {
if (test == null) {
test = new Test(); // Thread A. This thread is creating object.
}
}
}
return test;
}
}
已添加
如果不是单例模式的正确版本,volatile
关键字可以解决问题吗?即private volatile Test测试;
最佳答案
未知。这就是为什么这个实现被认为是错误的。
有可能 test = new Test()
首先创建对象,然后将对其的引用分配给 test
,然后才初始化它。
因此线程B
将引用对象,但它可能未初始化。
关于java - 以单例模式创建对象时,引用返回什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46234203/