2012-07-17 83 views
4

请看这个类,静态方法调用和输出。很多调用静态方法的单线程

public class OneThreadManyStaticCalls { 

public static final Calculator calculator = new Calculator(); 
    public static void main(String[] args) { 
     dummy(0, 1, 1); 
     dummy(0, 2, 2); 
     dummy(0, 3, 5); 
     dummy(0, 4, 44); 
     dummy(0, 5, 5); 
    } 

    public static void dummy(int a, int b, int expected) { 

     System.out.print(System.currentTimeMillis() + "\t"); 
     if (calculator.add(a, b) == expected) { 
      System.out.println("OK"); 
     } else { 
      System.err.println("NOK"); 
     } 
    } 
} 

我得到diffrent(从System.out.print订单)输出运行此程序。例如:

NOK 
    NOK 
    1342527389506 OK 
    1342527389506 OK 
    1342527389506 1342527389506 1342527389506 OK 

难道你们能解释我吗?(详情)为什么? 在此先感谢。 sznury

回答

12

System.err和System.out是在您的控制台窗口中交错的两个不同的流 - 它们不一定是同步的。 尝试使用System.*.flush()(从不说明,这似乎不起作用)强制处理输出,或将所有输出打印到同一个流。

public static void dummy(int a, int b, int expected) { 
    System.out.print(System.currentTimeMillis() + "\t"); 
    if ((a + b) == expected) { // I don't have your Calculator :< 
     System.out.println("OK"); 
    } else { 
     System.out.println("NOK"); 
    } 
} 

给出了这样的结果

1342528255764 OK 
1342528255764 OK 
1342528255764 NOK 
1342528255764 NOK 
1342528255764 OK 
1

@Jacob Raihle是正确的显示,这种情况改变你的System.err的呼叫到System.out的

public static void dummy(int a, int b, int expected) { 
    System.out.print(a+" "+b+" = "+expected); 
    if((a+b)==expected) 
     System.out.println(" OK"); 
    else 
     System.out.println(" NOK"); 

} 
2

一个简单的例子是

for (int i = 0; i <= 20; i++) 
    (i % 2 == 0 ? System.out : System.err).println(i); 

有即使两个流都进入控制台,也不保证两个流之间的顺序。

打印在一个运行(每次运行时改变)

1 
0 
3 
2 
5 
4 
7 
6 
9 
8 
11 
10 
13 
12 
15 
14 
17 
16 
19 
18 
20 

注:在我的IDE的System.err的线条出现在红

+0

你大概的意思是:“有秩序不能保证” – assylias 2012-07-17 13:23:06

+0

@assassias我做了,谢谢。 – 2012-07-17 13:35:15