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

pra*_*y G -2 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 7

问题出在你for-loop身上......

for (int i = 0; i < 1000; i++)
    synchronized (this) {
        x = 12;
        y = 12;
    }
System.out.print(x + " " + y + " ");
Run Code Online (Sandbox Code Playgroud)

这是一样的

for (int i = 0; i < 1000; i++) {
    synchronized (this) {
        x = 12;
        y = 12;
    }
}
System.out.print(x + " " + y + " ");
Run Code Online (Sandbox Code Playgroud)

现在应该突出问题.基本上,没有{...}块,只有synchornized循环执行块,1000次.

就像是...

for (int i = 0; i < 1000; i++) {
    synchronized (this) {
        x = 12;
        y = 12;
    }
    System.out.print(x + " " + y + " ");
}
Run Code Online (Sandbox Code Playgroud)

应该为你提供4000 12