我有这段简单的代码。
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
奇怪的是a=a
in zzz()
。当我拿出它时,它似乎没有任何改变。为什么会在那里?