2015-10-15 68 views
-2

我希望编译器为每个线程运行循环1000次,但输出是12 12 12 12.为什么会发生这种情况?这个循环为什么不执行1000次?

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(); 
    } 
} 
+9

检查你的循环'的for(int i = 0;我<1000;我++)'< - 缺少了什么的在这里结束 – MadProgrammer

+2

Ayyyyyyyyyyy!我刚才看到@MadProgrammer指的是什么。 –

+2

提示:代码完全按照您对它的说明 – MadProgrammer

回答

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

+0

即使问题的原始版本的'System.out.print'缩进与'for'循环相同,那么为什么你认为它的目的是在循环内?这个问题实际上并没有说这就是这个意图。 – Andreas

+1

@Andreas因为不然,为什么要问这个问题? OP想知道它为什么“只打印”12 12 12 12,这使我相信他们希望打印语句在循环内执行1000次 – MadProgrammer

+0

@Andreas看到后,我不在乎要记住有多少问题,关于为什么'if'和'loop'因为缺少'{...}而无法按预期工作,你只是假设 – MadProgrammer