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

2019-01-18 10:48发布

This question already has an answer here:

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:

enter image description here

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:

3条回答
小情绪 Triste *
2楼-- · 2019-01-18 11:14

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);
查看更多
▲ chillily
3楼-- · 2019-01-18 11:24
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.

查看更多
做自己的国王
4楼-- · 2019-01-18 11:29

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

查看更多
登录 后发表回答