Java 管道输入/输出流通信中存在大量延迟

aka*_*101 2 java multithreading inputstream outputstream

我正在制作一个使用管道输入/输出流(周围有一个对象输入/输出流包装器)的java应用程序。我在发送数据时遇到了相当大的延迟,并认为这是因为我最初的数据大小所致。但是,以下演示显示了在不同线程上通信时管道输入/输出流中的本机延迟。

public class Main{
public static long millis = 0;

public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    JButton button = new JButton("Press me");

    frame.getContentPane().add(button);
    frame.setSize(new Dimension(500, 500));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream(pis);

    button.addActionListener(e -> {
        try {
            pos.write((int) (Math.random() * 1000));
            //records time the packet was sent
            millis = System.currentTimeMillis();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });

    while (true) {
        System.out
                .println("recieved: " + pis.read() + "\n\tin time (ms): " + (System.currentTimeMillis() - millis));
    }

}
Run Code Online (Sandbox Code Playgroud)

}

对我来说,这个延迟通常约为 300-900 毫秒。这在我的应用程序中相当大。我想知道为什么延迟这么大?我该如何修复我的代码以减少延迟?

提前致谢。