可能有两个结果? (选择两个)
public class Cruiser {
private int a = 0;
public void foo() {
Runnable r = new LittleCruiser();
new Thread(r).start();
new Thread(r).start();
}
public static void main(String arg[]) {
Cruiser c = new Cruiser();
c.foo();
}
public class LittleCruiser implements Runnable {
public void run() {
int current = 0;
for (int i = 0; i < 4; i++) {
current = a;
System.out.print(current + ", ");
a = current + 2;
}
}
}
}
正确的答案是A和B,但是我不太明白这段代码是如何在较低级别上生成A的。
答案 0 :(得分:0)
A)0,2,4,0,2,4,6,6,
Thread-1: read a = 0;
Thread-2: read a = 0;
Thread-1: output 0, 2, 4
Thread-2: output 0
Thread-2: write 2 back to a
Thread-2: output 2, 4, 6
Thread-2: write 6 back to a;
Thread-1: read a = 6 and output 6