Welcome 微信登录

首页 / 软件开发 / JAVA / java io学习(三) 管道的简介,源码分析和示例

java io学习(三) 管道的简介,源码分析和示例2014-08-12 未知 管道(PipedOutputStream和PipedInputStream)的简介,源码分析和示例

本章,我们对java 管道进行学习。

java 管道介绍

在java中,PipedOutputStream和PipedInputStream分别是管道输出流和管道输入流。它们的作用是让多线程可以通过管道进行线程间的通讯。在使用管道通信时,必须将PipedOutputStream和PipedInputStream配套使用。使用管道通信时,大致的流程是:我们在线程A中向PipedOutputStream中写入数据,这些数据会自动的发送到与PipedOutputStream对应的PipedInputStream中,进而存储在PipedInputStream的缓冲中;此时,线程B通过读取PipedInputStream中的数据。就可以实现,线程A和线程B的通信。

PipedOutputStream和PipedInputStream源码分析

下面介绍PipedOutputStream和PipedInputStream的源码。在阅读它们的源码之前,建议先看看源码后面的示例。待理解管道的作用和用法之后,再看源码,可能更容易理解。此外,由于在“java io系列03之 ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)”中已经对PipedOutputStream的父类OutputStream进行了介绍,这里就不再介绍OutputStream。在“java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)”中已经对PipedInputStream的父类InputStream进行了介绍,这里也不再介绍InputStream。

1. PipedOutputStream 源码分析(基于jdk1.7.40)
package java.io; import java.io.*; public class PipedOutputStream extends OutputStream { // 与PipedOutputStream通信的PipedInputStream对象private PipedInputStream sink; // 构造函数,指定配对的PipedInputStreampublic PipedOutputStream(PipedInputStream snk)throws IOException {connect(snk);} // 构造函数public PipedOutputStream() {} // 将“管道输出流” 和 “管道输入流”连接。public synchronized void connect(PipedInputStream snk) throws IOException {if (snk == null) {throw new NullPointerException();} else if (sink != null || snk.connected) {throw new IOException("Already connected");}// 设置“管道输入流”sink = snk;// 初始化“管道输入流”的读写位置// int是PipedInputStream中定义的,代表“管道输入流”的读写位置snk.in = -1;// 初始化“管道输出流”的读写位置。// out是PipedInputStream中定义的,代表“管道输出流”的读写位置snk.out = 0;// 设置“管道输入流”和“管道输出流”为已连接状态// connected是PipedInputStream中定义的,用于表示“管道输入流与管道输出流”是否已经连接snk.connected = true;} // 将int类型b写入“管道输出流”中。// 将b写入“管道输出流”之后,它会将b传输给“管道输入流”public void write(int b)throws IOException {if (sink == null) {throw new IOException("Pipe not connected");}sink.receive(b);} // 将字节数组b写入“管道输出流”中。// 将数组b写入“管道输出流”之后,它会将其传输给“管道输入流”public void write(byte b[], int off, int len) throws IOException {if (sink == null) {throw new IOException("Pipe not connected");} else if (b == null) {throw new NullPointerException();} else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {throw new IndexOutOfBoundsException();} else if (len == 0) {return;}// “管道输入流”接收数据sink.receive(b, off, len);} // 清空“管道输出流”。// 这里会调用“管道输入流”的notifyAll();// 目的是让“管道输入流”放弃对当前资源的占有,让其它的等待线程(等待读取管道输出流的线程)读取“管道输出流”的值。public synchronized void flush() throws IOException {if (sink != null) {synchronized (sink) {sink.notifyAll();}}} // 关闭“管道输出流”。// 关闭之后,会调用receivedLast()通知“管道输入流”它已经关闭。public void close()throws IOException {if (sink != null) {sink.receivedLast();}}}