Java管道流线程通信 Java管道流实现线程间通信过程解析
lkc9 人气:0管道流
在Java语言中提供了各种各样的输入/输出流 Stream ,使我们能够很方便地对数据进行操作,其中管道流是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道流,另一个线程从输入管道流中读取数据。
通过使用管道,实现不同线程间的通信,而无须借助于类似临时文件之类的东西。
字节流
PipedInputStream 和 PipedOutputStream
字符流
PipedReader 和 PipedWriter
示例
public class PipeStreamTest { public static void main(String[] args) throws IOException, InterruptedException { WriteData writeData = new WriteData(); ReadData readData = new ReadData(); PipedReader reader = new PipedReader(); PipedWriter writer = new PipedWriter(); writer.connect(reader); new Thread(() -> { writeData.writeMethod(writer); }).start(); Thread.sleep(2000); new Thread(() -> { readData.readMethod(reader); }).start(); } static class WriteData { public void writeMethod(PipedWriter writer) { try { System.out.println("write :"); for (int i = 0; i < 300; i++) { String outData = "" + (i + 1); writer.write(outData); System.out.print(outData); } System.out.println(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } static class ReadData { public void readMethod(PipedReader reader) { try { System.out.println("read :"); char[] byteArray = new char[20]; int readLength = reader.read(byteArray); while (readLength != -1) { String newData = new String(byteArray, 0, readLength); System.out.print(newData); readLength = reader.read(byteArray); } System.out.println(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
运行结果如下:
加载全部内容