我希望编译器为每个线程运行1000次循环,但输出为12 12 12 12.为什么会发生这种情况?
public class Runy implements Runnable {
int x, y;
public void run() {
for (int i = 0; i < 1000; i++)
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
public static void main(String args[]) {
Runy run = new Runy();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t1.start();
t2.start();
}
}
答案 0 :(得分:7)
问题在于您的for-loop
...
for (int i = 0; i < 1000; i++)
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
与
相同for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
}
System.out.print(x + " " + y + " ");
现在应该突出问题。基本上,没有{...}
块,循环只执行synchornized
块,1000次。
像...一样的东西。
for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
应该为您提供4000 12