System.out & 的随机打印顺序System.err 调用 [英] Random printing order for System.out & System.err calls

查看:16
本文介绍了System.out & 的随机打印顺序System.err 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码片段

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {


    public static void main(String[] args)  {

        String str="";
        FileReader fileReader=null;

        try{


            // I am running on windows only  & hence the path :) 
            File file=new File("D:\Users\jenco\Desktop\readme.txt");
            fileReader=new FileReader(file);
            BufferedReader bufferedReader=new BufferedReader(fileReader);
            while((str=bufferedReader.readLine())!=null){
                System.err.println(str);
            }

        }catch(Exception exception){
            System.err.println("Error occured while reading the file : " + exception.getMessage());
            exception.printStackTrace();
        }
        finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                    System.out.println("Finally is executed.File stream is closed.");
                } catch (IOException ioException) {

                    ioException.printStackTrace();
                }
            }
        }

    }

}

当我多次执行代码时,我会随机得到如下输出,有时 System.out 语句会先打印在控制台中,有时 System.err 会先打印.下面是我得到的随机输出

When I execute the code multiple times , I get output randomly as below , sometimes the System.out statement gets printed first in the console , sometimes the System.err gets printed first. below are the random outputs that I get

Finally is executed.File stream is closed.
this is a text file 
and a java program will read this file.

输出 2

this is a text file 
and a java program will read this file.
Finally is executed.File stream is closed.

为什么会这样?

推荐答案

我相信这是因为您正在写入两个不同的输出(一个是标准输出,另一个是标准错误).这些可能在运行时由两个不同的线程处理,以允许在 java 执行期间写入两者.假设是这种情况,cpu 任务调度程序不会每次都以相同的顺序执行线程.

I believe this is because you are writing to two different outputs (one is standard out and the other standard error). These are probably handled by two different threads at runtime to allow writing to both during java execution. Assuming this is the case, the cpu task scheduler is not going to execute the threads in the same order every time.

如果您的所有输出都进入相同的输出流(即一切都进入标准输出或一切进入标准错误),则永远不应获得此功能.您永远无法保证标准错误与标准输出的执行顺序.

You should never get this functionality if all of your output is going to the same output stream (ie everything goes to standard out or everything goes to standard err). You will never be guaranteed execution order of standard error vs standard output.

这篇关于System.out & 的随机打印顺序System.err 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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