为什么这段代码等待 1000 毫秒而不是 500 毫秒?

Why does this code wait 1000ms instead of 500ms?

我不明白此代码如何打印 1000 而不是 500。我是否遗漏了什么?

    PipedOutputStream writer = new PipedOutputStream();
    PipedInputStream reader = new PipedInputStream();
    writer.connect(reader);
    BufferedReader stream = new BufferedReader(new InputStreamReader(reader));

    ScheduledExecutorService thread = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().build());
    thread.schedule(() -> {
        try {
            Thread.sleep(500);
            writer.write("test\n".getBytes(StandardCharsets.UTF_8));
        } catch (InterruptedException | IOException ignored) {
        }
    }, 0, TimeUnit.MILLISECONDS);

    long startTime = System.currentTimeMillis();
    stream.readLine();
    long duration = System.currentTimeMillis() - startTime;
    System.out.println(duration);

假设 PipedOutputStreamOutputStream 的子类,在给定的代码中它永远不会被刷新。

由于我们不知道 PipedOutputstream 的确切缓存或刷新行为,因此 可能 test\n 的字节未写入在 500 毫秒的等待过程完成后立即连接 PipedInputStream。相反,它会在稍后将第一块数据转发到其连接的接收器。

同样,假设 PipedOutputStreamOutputStream 的子类,刷新流将修复此行为。

try {
    Thread.sleep(500);
    writer.write("test\n".getBytes(StandardCharsets.UTF_8));
    writer.flush();
} catch (InterruptedException | IOException ignored) {
}