我正在制作一个使用管道输入/输出流的 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() + "ntin time (ms): " + (System.currentTimeMillis() - millis));
}
}
}
对我来说,这种延迟通常在 300-900 毫秒左右。这在我的应用程序中非常大。我想知道为什么延迟这么大?如何修复我的代码以减少延迟?
提前谢谢。
问题是输出未被刷新
参见 http://docs.oracle.com/javase/7/docs/api/java/io/PipedOutputStream.html#flush()