Java learning notes pipeline stream

Source: Internet
Author: User

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 ());}}}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.