2011-02-03 52 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,但沒有保證,而他們是如何混合在一起。

相關問題