java中System.out和System.err之间的竞争 [英] Race between System.out and System.err in java

查看:21
本文介绍了java中System.out和System.err之间的竞争的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个java代码:

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

    }
}

快速浏览一下代码,我们中的一些人可能会认为输出必须是 As 和 Bs 的输出.但事实并非如此!随机出现10个A字和10个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:

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

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

推荐答案

Why does this happen?

这是因为 outerr 是两个不同的输出流.但是,它们都在控制台上打印.因此,您不会将它们视为不同的流.此外,当您执行 out.println() 时,不能保证在执行语句后立即在控制台上看到输出.相反,字符串通常(取决于系统)存储在输出缓冲区中(如果您愿意的话),稍后由系统处理以将缓冲区的输出放到屏幕上.

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 :(

虽然,正如 Eng.Fouad 指出的那样,您可以使用 setOut(System.err)setErr(System.out) 来让它们有序,我仍然不建议您在实际将其放入应用程序时这样做(仅将其用于调试目的).

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.

这篇关于java中System.out和System.err之间的竞争的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆