Java pipeline stream read/write operations, used for communication between two threads

Source: Internet
Author: User

/* Java pipeline stream read/write operations are used between two threads
PipedOutputStream the PipedInputStream connection is a pipeline.
The MPs queue output stream can be written to the MPs queue. The MPs queue input stream can read data from the MPs queue.
This Decorator decoration design mode greatly enhances the java Stream Function
You can connect to the input and output streams of the pipeline when constructing a stream or connect to the stream through the connect function.

*/
Import java. io .*;
Class PipeTest
{
Public static void main (String [] args) throws Exception
{
PipedInputStream pis = new PipedInputStream (); // constructs the input stream of the pipeline.
PipedOutputStream pos = new PipedOutputStream (pis); // constructs the output stream and connects the input stream to form an MPS queue
New Procedure (pos). start (); // thread startup
New Consumer (pis). start (); // thread startup

}
}

Class Procedure extends Thread // Thread 1 pipeline output stream
{
Private PipedOutputStream pos;
Procedure (PipedOutputStream pos)
{
This. pos = pos;
}
Public void run ()
{
Try
{
Pos. write ("hello! Welcome you! ". GetBytes (); // write data to the MPs queue
}
Catch (Exception e)
{
E. printStackTrace ();
}
}
 
 
}

Class Consumer extends Thread
{
Private PipedInputStream pis;
Consumer (PipedInputStream pis)
{
This. pis = pis;
}
Public void run ()
{
Try
{

Byte [] buf = new byte [1, 100];
Int len = pis. read (buf, 0,100); // read data from the pipeline
System. out. println (new String (buf, 0, len ));
}
Catch (Exception e)
{
E. printStackTrace ();
}

 
}
 
 
 
 
 
 
 
 
}

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.