[JavaSE] I/O Stream (pipeline stream) and javaseio Stream pipeline
Previously, I/O streams were used to require an intermediate array. Pipeline streams can be directly input to the output stream. They are generally used with multiple threads. When no data is read from the stream, the current thread is blocked, no impact on other threads
Defines a class Read to implement the Runable interface, implements the run () method, and constructor transmits the PipedInputStream object
Read the data in the stream
Define a Write class to implement the Runable interface, implement the run () method, and construct a method to pass the PipedOutputStream object
Write Data in the stream
Obtain the PipedInputStream object.
Obtain the PipedOutputStream object.
Call the connect () method of the PipedInputStream object to connect to the output stream. Parameter: PipedOutputStream object
Enable two threads to execute read/write
Import java. io. IOException; import java. io. pipedInputStream; import java. io. pipedOutputStream;/*** Data Reading thread * @ author taoshihan **/class ReadPipe implements Runnable {private PipedInputStream in; public ReadPipe (PipedInputStream in) {this. in = in ;}@ Override public void run () {System. out. println ("start to read... If no data exists, it will block "); byte [] B = new byte [1024]; try {int len = in. read (B); String info = new String (B, 0, len); in. close (); System. out. println (info);} catch (IOException e) {e. printStackTrace () ;}}/ *** Data Writing thread * @ author taoshihan ***/class WritePipe implements Runnable {private PipedOutputStream out; public WritePipe (PipedOutputStream out) {this. out = out ;}@ Override public void run () {System. out. println ("Open Write... Latency: 5 seconds "); try {Thread. sleep (5000); out. write ("I am data ". getBytes (); out. close ();} catch (Exception e) {e. printStackTrace () ;}} public class PipeDemo {/*** @ param args * @ throws IOException */public static void main (String [] args) throws IOException {// connection pipe PipedInputStream in = new PipedInputStream (); PipedOutputStream out = new PipedOutputStream (); in. connect (out); // enable the Thread new Thread (new ReadPipe (in )). start (); new Thread (new WritePipe (out )). start ();}}