MPs queue stream and MPs queue
Link: http://www.bdqn.cn/news/201303/8270.shtml
A pipeline stream can transmit binary data between two threads.
A pipe stream is like a pipe where data is input at one end and data is output at another end. Usually two different threads are used to control them.
The usage is as follows:
[Html]View plaincopy
Import java. io. IOException;
Import java. io. PipedInputStream;
Import java. io. PipedOutputStream;
Public class PipedInputStreamTest {
Public static void main (String [] args ){
// MPs queue output stream
PipedOutputStream out = new PipedOutputStream ();
// Pipeline input stream
PipedInputStream in = null;
Try {
// Connect two pipeline streams. You can also call the connect (Piped...) method.
In = new PipedInputStream (out );
Thread read = new Thread (new Read (in ));
Thread write = new Thread (new Write (out ));
// Start the thread
Read. start ();
Write. start ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
Class Write implements Runnable {
PipedOutputStream pos = null;
Public Write (PipedOutputStream pos ){
This. pos = pos;
}
Public void run (){
Try {
System. out. println ("the program will write data in 3 seconds. Please wait... ");
Thread. sleep (3000 );
Pos. write ("wangzhihong". getBytes ());
Pos. flush ();
} Catch (IOException e ){
E. printStackTrace ();
} Catch (InterruptedException e ){
E. printStackTrace ();
} Finally {
Try {
If (pos! = Null ){
Pos. close ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
Class Read implements Runnable {
PipedInputStream pis = null;
Public Read (PipedInputStream pis ){
This. pis = pis;
}
Public void run (){
Byte [] buf = new byte [1, 1024];
Try {
Pis. read (buf );
System. out. println (new String (buf ));
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
If (pis! = Null ){
Pis. close ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}