我有這段簡單的代碼。分配數組變量的值給自己?
class A {
static volatile String[] a = new String[9];
public static void main(String[] args) {
new Thread() {
public void run() {
for (int i = 0; i < a.length; i++) {
while (a[i] == null);
System.out.println(a[i]);
}
}
}.start();
a[0] = "The";
zzz();
a[1] = "quick";
zzz();
a[2] = "brown";
zzz();
a[3] = "fox";
zzz();
a[4] = "jumped";
zzz();
a[5] = "over";
zzz();
a[6] = "the";
zzz();
a[7] = "lazy";
zzz();
a[8] = "cat";
zzz();
}
public static void zzz() {
try {
Thread.sleep(300);
} catch (Exception e) {}
a=a;
}
}
它輸出我所期望的:
$ javac A.java && java A
The
quick
brown
fox
jumped
over
the
lazy
cat
奇怪的是在zzz()
的a=a
。當我把它拿出來似乎沒有改變任何東西。爲什麼在那裏?
它什麼都不做。它可能在那裏添加了一個斷點。 –
分配給volitle將其發佈給其他線程嗎? –