2011-02-03 53 views
8

我当时正在糊弄我如何设置我的封装。程序执行是非顺序的。为什么?

但我的程序正在以意想不到的顺序执行。这里是我的,而简单的代码:

“主”:

package research.debug; 

public class Main { 

public static void main(String[] args) { 

    Boolean b = Boolean.TRUE ;  

    Debug.black.printVariable(b, "b") ; 
    Debug.red.printVariable(b, "b") ; 

    System.out.println("SUPPOSED to be inbetween...") ; 

    Debug.black.println("Hello") ; 
    Debug.red.println("Howdie") ; 

} 

} 

“调试”:

package research.debug; 

public class Debug { 

public static final Output black = new Output(Output.BLACK) ; 
public static final Output red = new Output(Output.RED) ; 

} 

最后, “输出”:

package research.debug; 

public class Output { 

public static final int BLACK = 0 ; 
public static final int RED = 1 ; 

private int outputMode = 0 ; 

public Output(int outputMode) { 

    this.outputMode = outputMode ; 

} 

public void println(String msg) { 

    if(outputMode == Output.BLACK) { 
     System.out.println("Printed with black font: " + msg) ; 
    } else { 
     System.err.println("Printed with red font: " + msg) ; 
    } 

} 

public void printVariable(Object variable, String variableName) { 

    println(variableName + " = \"" + variable + "\"") ; 

} 

} 

预期产出将为:

印有黑色字体:B = “真”

印有红色字体:B = “真”

应该是插图中......

印有黑色字体:你好

印有红色字体:Howdie

而是超出了预期秩序的,就像这样:

印有黑色字体:B = “真”

应该是插图中......

印有黑色字体:你好

印有红色字体:B =“真“

印刷用红色字体:Howdie

发生了什么事?

编辑:有时候“应该在之间”消息移动。没有我改变代码。

回答

18

System.out被缓冲,而System.err不是,它们是两个不同的流,并且你的一些消息会转到一个,另一个转到另一个。

因此,这些混合消息可能不会以预期的顺序出现,因为System.out的打印被延迟到缓冲区被刷新(手动或自动),而那些到System.err的应该立即写入。

您可以通过调用flush()方法手动刷新流。

+0

哇我从来不知道这一点。它用我的代码解释了一些事情 – TheLQ 2011-02-03 21:52:38

6

您正在打印至System.errSystem.out。尝试仅打印到System.out或使用System.out.flush()刷新缓冲区。

4

红色/黑色写入分别写入两个不同的流:System.errSystem.out

这些流在不同的时间是完全独立的。

这是保证(除非你使用多个线程)的唯一的事情是,无论你写System.out将出现在相同的顺序写的,同样对于System.err,但没有保证,而他们是如何混合在一起。

相关问题