[Java iO] _ pipeline stream notes
Objectives of this chapter:
Understanding the use of thread communication streams (pipeline streams)
Pipeline Flow
The main function of a pipeline stream is to communicate between two threads, namely, pipedoutputstream and pipedinputstream. If you want to output a pipeline, the output must linger on the input stream. The pipedoutputstream class has the following method for connecting to the pipeline.
Public void connect (pipinputstream SNK) throws ioexception
To implement pipeline stream, you can use pipeline output stream (pipedoutputstream) and pipeline input stream (pipedinputstream)
Import Java. io. *; Class send implements runnable {// Thread class private pipedoutputstream Pos = NULL; // The Public send () {This. pos = new pipedoutputstream (); // instantiate the output stream} public void run () {string STR = "Hello world !!! "; // Try {This. POS. write (Str. getbytes ();} catch (ioexception e) {e. printstacktrace ();} Try {This. POS. close ();} catch (ioexception e) {e. printstacktrace () ;}} public pipedoutputstream getpos () {// gets the output stream of this thread's pipeline return this. pos ;}}; class receive implements runnable {private pipedinputstream Pis = NULL; // The public receive () {This. pis = new pipedinputstream (); // instantiate input stream} public void run () {byte B [] = new byte [1024]; // receive content int Len = 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 ("received content:" + new string (B, 0, Len);} public pipedinputstream getpis () {return this. pis ;}}; public class pipeddemo {public static void main (string ARGs []) {send S = new send (); Receive r = new receive (); try {S. getpos (). connect (R. getpis (); // connection pipe} catch (ioexception e) {e. printstacktrace ();} new thread (s ). start (); // start the thread new thread (R ). start (); // start thread }};