Race between System.out and System.err in java [du

2019-01-18 10:37发布

问题:

This question already has an answer here:

  • Java: System.out.println and System.err.println out of order 6 answers

Please consider this java code:

public class CMain {
    public static void main(String[] args){

        for (int i = 0; i < 10; i++) {
            System.out.println("A");
            System.err.println("B");
        }

    }
}

By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:

Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...) Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:

  • Synchronization and System.out.println
  • Java: synchronizing standard out and standard error
  • Java: System.out.println and System.err.println out of order PS. I am using Eclipse as my IDE

回答1:

Why does this happen?

This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.

Solution :(

Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).

What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.



回答2:

They are different OutputStreams. If you really need to guarantee the order of printing them, use:

System.setErr(System.out);

or

System.setOut(System.err);


回答3:

Since there are two separate streams, the output you are giving is possible.