为什么这个循环不执行1000次?

时间:2015-10-15 02:26:52

标签: java

我希望编译器为每个线程运行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();
    }
}

1 个答案:

答案 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