我知道 System.out 是缓冲的。在显式刷新或程序终止之前,它不会将输出打印到终端。
我写了下面的程序来测试我的理解。 我认为程序终止时会打印程序的输出,因为我没有显式刷新流。 但是,一旦执行 print 就会打印输出,然后程序进入 5 秒 sleep 。
有人可以提出原因吗?
class PrintandSleep {
public static void main(String args[]) throws InterruptedException{
System.out.print("xyz");
Thread.sleep(5000);
}
}
最佳答案
原因是编写器是在标志自动刷新设置为 true 的情况下构建的。
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
在这种情况下,当我们调用write(String)
时,我们也会调用flush()
。
版本 8 的代码:
java.io.PrintStream
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
当您无法确定发生了什么时,请查看代码。
关于java - System.out.print() 在 java 中的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280091/