System.out.print()在java中的行为如何?

时间:2014-06-18 08:01:00

标签: java thread-sleep system.out

我知道System.out是缓冲的。在明确刷新或程序终止之前,它不会将输出打印到终端。

我写了下面的程序来测试我的理解。 我想我的程序输出会在程序终止时打印,因为我没有明确地刷新流。 但是一旦执行打印就会打印输出,然后程序进入5秒钟。

有人可以提出原因。

class PrintandSleep {
   public static void main(String args[]) throws InterruptedException{
       System.out.print("xyz");
       Thread.sleep(5000);
   }
}

1 个答案:

答案 0 :(得分:2)

原因是编写器的标志自动刷新设置为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;
        }
    }

当您无法确定发生了什么时,请查看代码。

相关问题