ArticleDirectory
- Pipeline stream (thread communication Stream)
Pipeline stream (thread communication Stream)
The main function of a pipeline stream is to communicate between two threads, namely, pipedoutputstream and pipedinputstream ),If you want to output a pipe, you must put the output on the input stream.In the pipedoutputstream class, you can use the following method to connect to the MPs queue:
Public void connect (pipedinputstream SNK) throws ioexception
Example: pipe streams are used for communication between threads.
1 Import Java. Io. ioexception;
2 Import Java. Io. pipedinputstream;
3 Import Java. Io. pipedoutputstream;
4
5 Class Send Implements Runnable {
6
7 Private Pipedoutputstream Pos; // MPs queue output stream
8 Public Send (){
9 Pos =New Pipedoutputstream ();
10 }
11 @ Override
12 Public Void Run (){
13 String STR = "Hello world! ";
14 Try {
15 POs. Write (Str. getbytes ());
16 }Catch (Ioexception e ){
17 E. printstacktrace ();
18 }
19 Try {
20 POs. Close ();
21 } Catch (Ioexception e ){
22 E. printstacktrace ();
23 }
24 }
25 Public Pipedoutputstream getpos (){
26 Return Pos;
27 }
28 }
29
30 Class Receive Implements Runnable {
31
32 Private Pipedinputstream Pis; // Pipeline input stream
33 Public Receive (){
34 Pis = New Pipedinputstream ();
35 }
36 @ Override
37 Public Void Run (){
38 Byte [] B = New Byte [1024];
39 Int Len = 0;
40 Try {
41 Len = PIs. Read (B );
42 } Catch (Ioexception e ){
43 E. printstacktrace ();
44 }
45 Try {
46 Pis. Close ();
47 } Catch (Ioexception e ){
48 E. printstacktrace ();
49 }
50 System. Out. println (New String (B, 0, Len ));
51 }
52 Public Pipedinputstream getpis (){
53 Return Pis;
54 }
55 }
56
57 Public Class Test23 {
58 Public Static Void Main (string [] ARGs ){
59 Send = New Send ();
60 Receive receive = New Receive ();
61 Try {
62 Send. getpos (). Connect (receive. getpis ()); // Connect MPs queue
63 } Catch (Ioexception e ){
64 E. printstacktrace ();
65 }
66 New Thread (send). Start (); // Start thread
67 New Thread (receive). Start ();// Start thread
68 }
69 }