该类继承自OutputStream
引入了IO包(本来就是这个包里的,引得没看懂)
该类的类头注释如下:
/** * A piped output stream can be connected to a piped input stream * to create a communications pipe. The piped output stream is the * sending end of the pipe. Typically, data is written to a * <code>PipedOutputStream</code> object by one thread and data is * read from the connected <code>PipedInputStream</code> by some * other thread. Attempting to use both objects from a single thread * is not recommended as it may deadlock the thread. * The pipe is said to be <a name=BROKEN> <i>broken</i> </a> if a * thread that was reading data bytes from the connected piped input * stream is no longer alive. * * @author James Gosling * @see java.io.PipedInputStream * @since JDK1.0 */
大意如下:
管道输出流可以与管道输入流连接成可用的通信管道
管道输出流是管道的发送段
典型情况下,数据会被某线程写入管道输出流,然后会被与其链接的管道输入流通过其他线程读出
建议使用这两个类时不要使用单线程(可能会造成死锁)
如果某个线程正从连接的管道输入流中读取数据字节,但该线程不再处于活动状态,则该管道被视为断裂
该类含有如下的成员变量:
与其相连接的管道输入流
private PipedInputStream sink;
该类含有如下的成员方法:
构造函数(与给定的输入流相链接
public 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;//绑定对象 snk.in = -1;//缓存空间偏移量修改 snk.out = 0; snk.connected = true; }
写入一个字节
public void write(int b) throws IOException { if (sink == null) { throw new IOException("Pipe not connected"); } sink.receive(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); }
刷新输出流(写出底层流缓冲的数据,并且唤醒沉睡的reader线程
public synchronized void flush() throws IOException { if (sink != null) { synchronized (sink) {//保证控制权 sink.notifyAll();//唤起reader线程读取缓冲数据 } } }
关闭管道(释放资源
public void close() throws IOException { if (sink != null) { sink.receivedLast();//关闭了写入端,并且唤醒读取线程读取剩余缓存 } }
该类的操作主要都是通过调用PipedInputStream类,相当于把大部分操作都封装到输入流里了,所以在学习这个之前建议先去学习PipedInputSream