程序执行是非顺序的。为什么?

时间:2011-02-03 21:27:13

标签: java encapsulation

我在如何设置封装时无所事事。

但我的程序是以意想不到的顺序执行的。这是我非常简单的代码:

“主要”:

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 =“true”

用红色字体打印:b =“true”

支持介于......之间......

印有黑色字体:Hello

印有红色字体:Howdie

但反过来的是预期的顺序,如下所示:

用黑色字体打印:b =“true”

支持介于......之间......

印有黑色字体:Hello

用红色字体打印:b =“true”

印有红色字体:Howdie

发生了什么事?

编辑:有时候“假定介于两者之间”的消息会四处移动。没有我改变代码。

3 个答案:

答案 0 :(得分:18)

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

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

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

答案 1 :(得分:6)

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

答案 2 :(得分:4)

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

这些流完全独立,在不同时间刷新。

唯一可以保证的是(除非你使用多个线程)是你写给System.out的任何内容都会以写入的顺序出现,同样对System.err也是如此,但不保证他们是如何混在一起的。

相关问题