系统外部错误Java中的System.out交错 [英] System.out.err & System.out interleaving in Java

查看:74
本文介绍了系统外部错误Java中的System.out交错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要弄清楚执行一个算法需要花费多少时间,我在main方法中执行此操作,但是由于它与System.print交错,因此不会打印时间.

To work out how much time is taken to perform an algorithm, I do this in the main method, but it does not print the time as it gets interleaved with System.print.

long startTime = System.currentTimeMillis();     
A1.Print(2);
long endTime = System.currentTimeMillis();
System.err.print(endTime - startTime);

并且如果A类是这样的话:

and if the class A is this:

public class A{

    public void Print(int n){
        for(int i = 0; i <=n; i++){
        System.out.println(i)
    }
}

它打印

0

1

2

在这一行中,这是应该经过该循环的时间,但它根本不会,因此不会像这样打印:

and in this line it is the amount of time that is supposed go through that loop, but it simply won't, so it won't print like this:

0

1

2

1

此处最后一行或1是算法所用的毫秒数.教科书上说您必须使用System.err.并找出防止交错的方法.

Here the last line or 1 is the millisecond taken for the algorithm. The textbook says you MUST use System.err. and figure out a way to prevent interleaving.

推荐答案

您可以所以输出在同一个流中.它们使用两个不同的流,所以这就是为什么要交织的原因.

so the output is in the same stream. They use two different streams so that's why you get interleaving.

对于您的代码,它将是:

For your code it would be:

long startTime = System.currentTimeMillis();    
System.setErr(System.out); 
A1.Print(50);
long endTime = System.currentTimeMillis();
System.err.print(endTime - startTime);

这篇关于系统外部错误Java中的System.out交错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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