Mastering the use of thread traffic (pipeline flow)
The main function of pipeline flow is to communicate between two threads, which is divided into pipeline input stream (Pipeoutputstream) and pipeline output stream (Pipeinputstream).
If you want to do pipeline output, you must hang the output over the input stream and have the following method on the Pipeoutputstream to connect the pipe.
void Connect (pipedinputstream SNK) connects this pipeline output to the receiver.
To connect inputs and outputs, you must use this method,
Pipeoutputstream Output Method:
The void write(byteintint len )byte array is written to the pipeline output stream.
Pipeinputstream Input Method: How to read a file
The data that will connect the input stream of the Pipeoutputstream object instance, The contents are read into the array through the Read method.
int Read (byteintint len) will have a maximum of Len data bytes in a byte array .
Instance code:
Packageclass set;ImportJava.io.* ;classSendImplements Runnable{//Thread Class PrivatePipedOutputStream pos =NULL;//Pipe Output Stream PublicSend () { This. pos =NewPipedOutputStream ();//instantiate the output stream } Public voidrun () {String str= "Hello world!!!";//the content to output Try{ This. Pos.write (Str.getbytes ()); }Catch(IOException e) {e.printstacktrace (); } Try{ This. Pos.close (); }Catch(IOException e) {e.printstacktrace (); } } PublicPipedOutputStream GetPos () {//get the pipeline output stream for this thread return This. Pos; }};classReceiveImplementsrunnable{PrivatePipedInputStream PiS =NULL;//Pipeline input Stream PublicReceive () { This. PiS =NewPipedInputStream ();//instantiating an input stream } Public voidrun () {byte b[] = new byte[1024]; Receive Content intLen = 0 ; Try{ len = This.pis.read (b); Read Content}Catch(IOException e) {e.printstacktrace (); } Try{ This. Pis.close ();//Close}Catch(IOException e) {e.printstacktrace (); } System.out.println ("The content Received is:" +New String (b,0 , Len)) ;//Note that this is the output of the data for the read-in array, not the Pipeinputstream instance object output ,} PublicPipedInputStream Getpis () {return This. PiS; }}; Public classpipeddemo{ Public Static voidMain (String args[]) {Send s=NewSend (); Receive R=NewReceive (); Try{ s.getpos (). Connect (R.getpis ()); //Connection Piping}Catch(IOException e) {e.printstacktrace (); } new Thread (s). Start (); Start Thread NewThread (R). Start ();//Start Thread }};
After Pipeinputstream reads the file, the data that is read is present in an instance of the Pipeinputstream object, and the type is byte.
Summarize:
Development of the direct development of multi-threaded programs, this program, just let the reader deepen the process of reading and writing, understand, how to communicate between threads.
IO programming for Java: Pipeline flow