这篇文章将为大家详细讲解有关PipedReader与PipedWriter有哪些不同的地方,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

PipedWriter与PipedReader的区别
1. PipedWriter 源码
package java.io;
public class PipedWriter extends Writer {
// 与PipedWriter通信的PipedReader对象
private PipedReader sink;
// PipedWriter的关闭标记
private boolean closed = false;
// 构造函数,指定配对的PipedReader
public PipedWriter(PipedReader snk) throws IOException {
connect(snk);
}
// 构造函数
public PipedWriter() {
}
// 将“PipedWriter” 和 “PipedReader”连接。
public synchronized void connect(PipedReader snk) throws IOException {
if (snk == null) {
throw new NullPointerException();
} else if (sink != null || snk.connected) {
throw new IOException("Already connected");
} else if (snk.closedByReader || closed) {
throw new IOException("Pipe closed");
}
sink = snk;
snk.in = -1;
snk.out = 0;
// 设置“PipedReader”和“PipedWriter”为已连接状态
// connected是PipedReader中定义的,用于表示“PipedReader和PipedWriter”是否已经连接
snk.connected = true;
}
// 将一个字符c写入“PipedWriter”中。
// 将c写入“PipedWriter”之后,它会将c传输给“PipedReader”
public void write(int c) throws IOException {
if (sink == null) {
throw new IOException("Pipe not connected");
}
sink.receive(c);
}
// 将字符数组b写入“PipedWriter”中。
// 将数组b写入“PipedWriter”之后,它会将其传输给“PipedReader”
public void write(char cbuf[], int off, int len) throws IOException {
if (sink == null) {
throw new IOException("Pipe not connected");
} else if ((off | len | (off + len) | (cbuf.length - (off + len))) < ) {
throw new IndexOutOfBoundsException();
}
sink.receive(cbuf, off, len);
}
// 清空“PipedWriter”。
// 这里会调用“PipedReader”的notifyAll();
// 目的是让“PipedReader”放弃对当前资源的占有,让其它的等待线程(等待读取PipedWriter的线程)读取“PipedWriter”的值。
public synchronized void flush() throws IOException {
if (sink != null) {
if (sink.closedByReader || closed) {
throw new IOException("Pipe closed");
}
synchronized (sink) {
sink.notifyAll();
}
}
}
// 关闭“PipedWriter”。
// 关闭之后,会调用receivedLast()通知“PipedReader”它已经关闭。
public void close() throws IOException {
closed = true;
if (sink != null) {
sink.receivedLast();
}
}
}