class C {
Object o;
public void set(Object o){
if(this.o == null){
this.o = o;
}
}
public Object get(){
return o;
}
}
C c = new C();
C c = new C();
Thread#1
Object o1 = c.get(); // 1
Object o2 = c.get(); // 2
Thread#2
c.set(new Object());
難道o2 == null && o1 != null
? 爲什麼?Java內存模型和併發讀取
要清楚我的意思是我編輯:
如果我們有以下的情況:,
C c = new C(); // it is given at beginning
1) Object o2 = c.o; // o2 is null. This operation was **reordered** before O `o1 = c.o. The JVM can do it because JMM allows do it.
2) c.o = new Object()` //Thread #2 was executed
3) O o1 = c.o // o1 is not null while o2 is.
我不明白'get()'返回除'null'之外的任何東西是可能的。如果參數爲空,'o'永遠不會被初始化,'set()'只會修改'o' –
不,因爲c1在c2之前被檢索到,並且在任何其他線程中沒有東西可以將其恢復爲空。然而,c2可能非空而c1爲空 – litelite