The main function of a pipe stream is to connect two threads for communication. Pipeline streams are also divided into two types: PipedInputStream and PipedOutputStream, and pipeline stream (PipedReader and PipedWriter. A PipedInputStream object must be connected to a PipedOutputStream object to generate a communication pipeline. PipedOutputStream can write data to the pipeline, and PipedInputStream can read data written by PipedOutputStream from the pipeline. Sample Code for implementing inter-thread communication in pipelines:
Sender class: import java. io. IOException; import java. io. pipedOutputStream; public class Sender extends Thread {private PipedOutputStream out = null; public PipedOutputStream getOutputStream () {this. out = new PipedOutputStream (); return out;} public void run () {String s = new String ("Runner Er, hello! "); Try {out. write (s. getBytes (); out. close ();} catch (IOException e) {System. out. println (e. getMessage () ;}} Eeceiver class: import java. io. IOException; import java. io. pipedInputStream; public class Eeceiver extends Thread {privatePipedInputStream in = new PipedInputStream (); publicPipedInputStream getinputStream () {return in;} publicpipvoid run () {String s = null; byte [] buf = new byte [1024]; try {int len = in. read (buf); s = new String (buf, 0, len); System. out. println ("received message:" + s); in. close ();} catch (IOException e) {System. out. println (e. getMessage () ;}} Pipedemo class: import java. io. IOException; import java. io. pipedInputStream; import java. io. pipedOutputStream; public class pipedemo {publicstatic void main (String args []) {try {Sendersender = new Sender (); Eeceiverreceiver = new Eeceiver (); PipedOutputStreamout = sender. getOutputStream (); PipedInputStreamin = runner er. getinputStream (); out. connect (in); sender. start (); worker er. start ();} catch (IOException e) {System. out. println (e. getMessage ());}}}