System.out和System.err调用的随机打印顺序

che*_*rit 4 java file-io

请参阅下面的代码段

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

    }

}
Run Code Online (Sandbox Code Playgroud)

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

输出1

Finally is executed.File stream is closed.
this is a text file 
and a java program will read this file.
Run Code Online (Sandbox Code Playgroud)

输出2

this is a text file 
and a java program will read this file.
Finally is executed.File stream is closed.
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Sco*_*ott 6

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

如果所有输出都转到相同的输出流(即所有输出都标准输出或一切都符合标准错误),则永远不应该获得此功能.永远不会保证标准错误与标准输出的执行顺序.

  • 不需要谈论两个不同的线程......关键是标准输出和错误是不同的流在这里:-) (4认同)