System.out 和 System.err 调用的随机打印顺序[重复]

2024-01-13

请参阅下面的代码片段

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 首先打印。下面是我得到的随机输出

Output 1

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

Output 2

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

为什么会这样呢?


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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

System.out 和 System.err 调用的随机打印顺序[重复] 的相关文章

随机推荐