给定:
public class Thread1 {
int x = 0;
public class Runner implements Runnable {
public void run() {
int current = 0;
for (int i = 0; i < 4; i++) {
current = x;
System.out.print(current + " ");
x = current + 2;
}
}
}
public void go() {
Runnable r1 = new Runner();
new Thread(r1).start();
new Thread(r1).start();
}
public static void main(String[] args) {
new Thread1().go();
}
}
哪两个是可能的结果? (选择两项)
一个。 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
我选择了 A 和 B,但不确定这是否是正确答案。
最佳答案
首先,D. 和 E. 出局了。由于 i
作用于函数局部,我们知道将有 8 个数字。
现在
B. 0, 2, 4, 6, 8, 10, 2, 4,
不正确。为什么?为了打印最后两个位置,每个线程必须写入变量 x
至少两次。此时 x
的最小值为 4
。这意味着无论竞争条件如何,最后两个值都应大于或等于 4
。
编辑
C
是完全可能的。没有同步并不意味着不可能有所谓的串行执行(即好像线程一个接一个地执行)。并发的教训是你不知道线程将如何交错
C. 0, 2, 4, 6, 8, 10, 12, 14,
发生例如:
- 当第一个线程在第二个开始之前完成更新
x
- 当第一个线程在第一个
current = x;
之前挂起时,第二个线程完成执行,第一个继续执行。 - 吨 其他案例。
正如 Brian Goetz 所说:
"Writing correct programs is hard; writing correct concurrent programs is harder."
关于java - 两个线程作用于同一个可运行对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239922/