In this chapter, we study Pipedreader and PipedWriter. Like "PipedInputStream and PipedOutputStream", they can be used for pipe communications.
PipedWriter is a character pipeline output stream that inherits from writer.
Pipedreader is a character pipeline input stream that inherits from writer.
The role of PipedWriter and Pipedreader is to communicate between threads through a pipeline. PipedWriter and Pipedreader must be used to support the use of piping communications.
PipedWriter and Pipedreader Source analysis
1. PipedWriter source code (based on jdk1.7.40)
Package java.io;
public class PipedWriter extends Writer {//PipedWriter communication Pipedreader object private Pipedreader sink;
PipedWriter Close Tag Private Boolean closed = false;
constructor that specifies the paired Pipedreader public PipedWriter (Pipedreader SNK) throws IOException {connect (SNK);
}//Constructor public PipedWriter () {}///"PipedWriter" and "Pipedreader" are connected. Public synchronized void Connect (Pipedreader snk) throws IOException {if (SNK = null) {throw new Nu
Llpointerexception ();
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; Set "Pipedreader" and "PipedWriter" as connected states//connected are defined in Pipedreader to indicate whether "Pipedreader and pipedwriter" have connected SN K.connecTed = true;
//write a character C to "PipedWriter".
After writing C to "PipedWriter", it transmits C to "Pipedreader" public void write (int c) throws IOException {if (sink = null) {
throw new IOException ("Pipe not Connected");
} sink.receive (c);
//writes character array B to "PipedWriter".
After the array B is written to "PipedWriter", it transmits it to "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))
< 0) {throw new indexoutofboundsexception ();
} sink.receive (Cbuf, off, Len);
}//Empty "PipedWriter".
The Notifyall () of the "Pipedreader" is invoked, and the purpose is to let "pipedreader" discard the current resource, so that the other waiting thread (the thread waiting to read the PipedWriter) reads the value "PipedWriter". Public synchronized void Flush () throws IOException {if (sink!= null) {if (Sink.closedbyreader | | c losed){throw new IOException ("Pipe closed");
} synchronized (sink) {sink.notifyall ();
}}//Turn off "PipedWriter".
When closed, Receivedlast () is invoked to notify the "Pipedreader" that it has been closed.
public void Close () throws IOException {closed = true;
if (sink!= null) {sink.receivedlast (); }
}
}