19

请考虑这个java代码:

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

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

    }
}

通过快速查看代码,我们中的一些人可能会认为输出必须是 As 和 Bs 的打印。然而不是!随机出现10个A字和10个B字。像这样的东西:

在此处输入图像描述

这是为什么?以及它的解决方案是什么,以便交替显示 As 和 Bs ( ABABAB ...) 在我问这个问题之前,我检查了其他几个类似的问题的解决方案,但不适用于我的案例!我在这里带来了一些:

4

3 回答 3

11
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.

于 2013-02-28T23:07:07.137 回答
5

他们是不同OutputStream的s。如果您确实需要保证打印顺序,请使用:

System.setErr(System.out);

或者

System.setOut(System.err);
于 2013-02-28T23:10:11.143 回答
0

由于有两个单独的流,因此您提供的输出是可能的。

于 2013-02-28T23:03:41.353 回答