[英]PrintStream.println() behavior — Java / Python / Any Language
I think I'm having a little doubt with the concept of println()
method. 我想我对
println()
方法的概念有点怀疑。
I tried the following code: 我尝试了以下代码:
Object one = 1;
System.out.println(one);
one = "String";
System.out.println(one);
one = null;
System.out.println(one.toString()); // To explicitly throw an Exception
The expected output is and indeed I get this sometimes: 预期的输出是,确实有时我会得到:
1
String
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
However running multiple times, we can see see the following outputs, as well: 但是运行多次,我们还可以看到以下输出:
1
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
String
or 要么
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
1
String
Then, I thought of performing similar operation in Python. 然后,我想到了在Python中执行类似的操作。 Below is the snippet:
以下是代码段:
var = 'Hello';
print var;
var = 6;
print var;
del var;
print var;
And yes, the similar behavior. 是的,类似的行为。 The traceback message output preference cannot be determined.
无法确定回溯消息输出首选项。 Sometimes, its printed at the top, sometimes in the middle or sometimes at the bottom.
有时,其打印在顶部,有时在中间,有时在底部。
I think it must be something related to synchronized
buffer output. 我认为这一定与
synchronized
缓冲区输出有关。 Not sure, it could be. 不知道可能是这样。
Can anyone help me out in getting this concept? 谁能帮我解决这个问题?
This is due to the fact you have two output streams System.out
and System.err
and they are not co-ordinated or always in order. 这是由于您有两个输出流
System.out
和System.err
,它们并不协调或始终处于顺序状态。
You can do 你可以做
Object one = 1;
System.err.println(one);
Object one = "String";
System.err.println(one);
one = null;
System.out.println(one.toString());
or 要么
Object one = 1;
System.out.println(one);
Object one = "String";
System.out.println(one);
one = null;
try {
System.out.println(one.toString());
} catch (Exception e) {
e.printStackTrace(System.out);
}
What you should do is use a logger. 您应该做的是使用记录器。 The logger will be configured to write everything to either System.out or System.err so you will get a predictable out put.
记录器将配置为将所有内容写入System.out或System.err,这样您将获得可预测的输出。
I think it must be something related to synchronized buffer output.
我认为这一定与同步缓冲区输出有关。
Both System.out
and System.err
are synchronized. System.out
和System.err
都是同步的。 They don't use the same lock as they are not the same object, though this wouldn't matter because the two streams they write to can be read in any order. 它们不使用相同的锁,因为它们不是同一对象,尽管这无关紧要,因为写入它们的两个流可以按任何顺序读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.