以下是仔细检查单例模式的实现。线程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;
这必须是静态的...:***公开测试的get(){***若不是没有因为你将需要一个Test类的实例,以便能够调用get方法 –
@ΦXocę웃Пepeúpaツ对不起,我对它进行了修改。 – user7328234