1 How to use
PipedOutputStream and PipedInputStream are pipeline output streams and pipe input streams, which enable communication between threads.
The main process for using pipelines for communication between threads is as follows: Creates an output stream out and an input stream in, binds out and in, the data that is written in the out is synchronized in the buffer in which it is written, in the case where the data written out is written to the buffer in, and there is no data buffer in the out. 1.1 Method Introduction
PipedOutputStream provides the following APIs:
Constructor public
PipedOutputStream (PipedInputStream SNK);
public PipedOutputStream ();
Public synchronized void Connect (PipedInputStream SNK); Bind PipedOutputStream and Pipedinputsteam to public
void write (int b);//write to output B public
void Write (byte b[], int o FF, int len); Writes byte array b public
synchronized void Flush () to output,/flushes the buffer, notifies other input read data public
void close
(); PipedOutputStream provides the following APIs:
//Constructor public
pipedinputstream (PipedOutputStream src);
Public PipedInputStream (pipedoutputstream src, int pipesize);
public void Connect (PipedOutputStream src); Bind PipedOutputStream and Pipedinputsteam
protected synchronized void receive (int b);//write to input buffer b
synchronized void receive (byte b[], int off, int len); Write byte array to input B public
synchronized int read ();//read buffer next byte public
synchronized int read (byte b[], int out, in T len)/read buffer byte array to b public
synchronized int available ();//buffer readable byte array number public
void close ();
1.2 Using the example
/** * Producer Thread */public class Producer extends thread {//output stream private pipedoutputstream out = new Pipedoutputstrea
M ();
Construction method Public Producer (PipedOutputStream out) {this.out = out;
@Override public void Run () {writemessage ();
private void Writemessage () {StringBuilder sb = new StringBuilder ("Hello world!!!");
try {out.write (sb.tostring (). GetBytes ());
Out.close ();
catch (IOException e) {e.printstacktrace (); }}/** * Consumer thread/public class Consumer extends thread {//input stream, default buffer size is 1024 private pipedinputstream in
= new PipedInputStream ();
Construction method Public Consumer (PipedInputStream in) {this.in = in;
@Override public void Run () {readmessage ();
private void Readmessage () {byte [] buf = new byte[1024];
try {int len = In.read (BUF); System.out.println ("Buffer ofContent is: "+ new String (buf, 0, Len));
In.close ();
catch (IOException e) {e.printstacktrace (); @org. Junit.test public void testpiped () {/** * process * 1 Establish input Output stream * 2 binding input loss
Out stream * 3 Write data to buffer * 4 Read buffer data * * pipedoutputstream out = new PipedOutputStream ();
PipedInputStream in = new PipedInputStream ();
Producer Producer = new Producer (out);
Consumer Consumer = new Consumer (in);
try {out.connect (in);
Producer.start ();
Consumer.start ();
catch (IOException e) {e.printstacktrace (); }
}
The results of the operation are as follows:
The contents of the buffer are: Hello world!!!
2 Source Analysis
According to the demo program running process analysis source code, mainly has the construction method, connect, out write, in read and so on. construction method of 2.1 PipedOutputStream
/**
* Creates a piped output stream connected to the specified piped
* input stream. Data bytes written to this stream would then be
* available as input from <code>snk</code>.
*
* @param SNK the piped input stream to connect to.
* @exception IOException If an I/O error occurs.
* * Public
PipedOutputStream (PipedInputStream SNK) throws IOException {
connect (SNK);
}
/**
* Creates a piped output stream, that isn't yet connected to a
* piped input stream. It must is connected to a piped input stream,
* either by the receiver or the sender, before being.
* *
@see java.io.pipedinputstream#connect (java.io.PipedOutputStream)
* @see Java.io.pipedoutputstream#connect (java.io.PipedInputStream)
*/public
PipedOutputStream () {
}
construction method of 2.2 PipedInputStream
/** * Creates a <code>PipedInputStream</code> so, it is * connected to the piped output stream * <co
De>src</code> and uses the specified pipe size for * The pipe ' s buffer.
* Data bytes written to <code>src</code> would then * is available as input from this stream.
* @param src The stream to connect to.
* @param pipesize the size of the pipe ' s buffer.
* @exception IOException If an I/O error occurs.
* @exception illegalargumentexception If {@code pipesize <= 0}. * @since 1.6 */public PipedInputStream (pipedoutputstream src, int pipesize) throws IOException {INITPI
PE (pipesize);
Connect (SRC);
PipedInputStream (PipedOutputStream src) throws IOException {This (src, default_pipe_size); /** * Creates a <code>PipedInputStream</code> so, it is not yet * {@linkplain #connect (JAVA.IO.PIPEDOUTP Utstream) Connected} and * uses the specified pipe size for the pipe ' s buffer.
* It must be {@linkplain java.io.pipedoutputstream#connect (* java.io.PipedInputStream) * connected} to a <code>
Pipedoutputstream</code> before being used.
* * @param pipesize the size of the pipe ' s buffer.
* @exception illegalargumentexception If {@code pipesize <= 0}. * @since 1.6 */public pipedinputstream (int pipesize) {initpipe (pipesize);} public PipedInputStream () {in
Itpipe (default_pipe_size); } 2.3 PipedOutputStream Connect Method
/** * Connects this piped output stream to a receiver. If This object * are already connected to some piped input stream, a * <code>IOException</code> is THR
Own. * <p> * If <code>snk</code> is a unconnected piped input stream and * <code>src</code> is An unconnected piped output stream, they may * is connected by either the call: * <blockquote><pre> * src. Connect (SNK) </pre></blockquote> * or the call: * <blockquote><pre> * snk.connect (SRC) </pre&
Gt;</blockquote> * The two calls have the same effect.
* * @param snk the piped input stream to connect to.
* @exception IOException If an I/O error occurs. * * Public synchronized void Connect (PipedInputStream snk) throws IOException {if (SNK = null) {throw new Nu
Llpointerexception ();
else if (sink!= null | | snk.connected) {throw new IOException ("Already connected"); } sink = SNK;
Set input stream snk.in =-1; Write buffer subscript snk.out = 0; Read buffer subscript snk.connected = true; Set Connection Status} 2.4 PipedOutputStream Write Method
/** * Writes the specified <code>byte</code> to the piped output stream.
* <p> * Implements The <code>write</code> method of <code>outputstream</code>.
* * @param b the <code>byte</code> to be written. * @exception IOException If the pipe is <a href= #BROKEN > Broken</a>, * {@link #connect (java.io.Piped
InputStream) unconnected}, * closed, or if an I/O error occurs. */public void write (int b) throws IOException {if (sink = null) {throw new IOException ("Pipe not connecte
D "); } sink.receive (b); Direct call input stream method operation input Stream buffer}/** * Receives a byte of data.
This method would block if no input is * available. * @param b The byte being received * @exception IOException If The pipe is <a href= "#BROKEN" > <code>broken< ;/code></a>, * {@link #connect (java.io.PipedOutputStream) unconnected}, * closed, or if an i/
O error occurs. * @since JDK1.1 */protected synchronized void receive (int b) throws IOException {checkstateforreceive ();//check writable State WR Iteside = Thread.CurrentThread ();
Gets the input streamline path if (in = = out) full, that is, the buffer data has been read awaitspace ();
if (in < 0) {//buffer is empty in = 0;
out = 0; } buffer[in++] = (byte) (b & 0xFF);
Write, limited to 8-bit if (in >= buffer.length) {//in = 0; }
} 2.5 PipedInputStream Read Method
/** * Reads the next byte of data from this piped input stream. The * value byte is returned as a <code>int</code> in the range * <code>0</code> to <code>
; 255</code>.
* This method blocks until input data are available, the end of the * stream is detected, or a exception is thrown.
* @return The next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception IOException if the pipe is * {@link #connect (java.io.PipedOutputStream) unconnected}, *
<a href= "#BROKEN" > <code>broken</code></a>, closed, * or if an I/O error occurs. */public synchronized int read () throws IOException {if (!connected) {throw new IOException ("Pipe not con
Nected ");
else if (Closedbyreader) {throw new IOException ("Pipe closed"); else if (writeside!= null &&!writeside.isalive () &&!CLOSEDBYWRITER && (in < 0)) {throw new IOException (' Write end Dead '); } readside = Thread.CurrentThread ();
Gets the current read thread int trials = 2; while (in < 0) {//No readable content if (closedbywriter) {/* Closed by writer, return EOF * * Retu
rn-1; } if ((Writeside!= null) && (!writeside.isalive ()) && (--trials < 0)) {throw new
IOException ("Pipe broken"); }/* Might be a writer waiting * * notifyall ();
The notification is written to try {wait (1000);
The catch (Interruptedexception ex) {throw new java.io.InterruptedIOException (); int ret = buffer[out++] & 0xFF;
Read bytes if (out >= buffer.length) {//over buffer length, read from scratch, write as, so can be guaranteed to read and write in the same order out = 0;
} if (in = = out) {//No readable content/* now empty */in =-1;//receive the out to 0} return ret; }Reference:
[1] http://www.cnblogs.com/skywang12345/p/io_04.html
[2] Http://www.2cto.com/kf/201402/279143.html
[3] Http://www.cnblogs.com/meng72ndsc/archive/2010/12/23/1915358.html