Program execution is not sequential. What for?

I tricked myself into how I could customize my encapsulation.

But my program runs in unexpected order. Here is my pretty simple code:

"Main":

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" ) ; } } 

Debugging:

 package research.debug; public class Debug { public static final Output black = new Output( Output.BLACK ) ; public static final Output red = new Output( Output.RED ) ; } 

And finally, “Conclusion”:

 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 + "\"" ) ; } } 

And the expected result:

Printed in black: b = "true"

Printed in red: b = "true"

MEETS be between ...

Printed in black: Hello

Printed in red: Howdie

But instead, it leaves the expected order, for example:

Printed in black: b = "true"

MEETS be between ...

Printed in black: Hello

Printed in red: b = "true"

Printed in red: Howdie

What's happening?

EDIT: Sometimes the message “Assume Between Them” moves around. Change the code without me.

+8
java encapsulation
source share
3 answers

System.out buffered, but System.err is not, these are two different threads, and some of your messages go to one and some to the other.

Consequently, these mixed messages may not be displayed in the expected order, since fingerprints on System.out delayed until the buffer is flushed (manually or automatically), while those that should be System.err must be written immediately .

You can clear the stream manually by calling the flush() method.

+18
source share

You are printing to System.err and System.out . Try printing only System.out or use System.out.flush() to clear the buffers.

+6
source share

Red / black entries are recorded in two different streams: System.err and System.out respectively.

These threads are completely independent and are reset at different times.

The only thing guaranteed (if you do not use multiple threads) is that what you write to System.out will be displayed in the same order that it is written, as well as to System.err , but there are no guarantees as to how they mixed together.

+4
source share

All Articles