管道流(线程通信流)

管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流(PipedOutputStream)、管道输入流(PipedInputStream),如果想要进行管道输出,则必须要把输出流连在输入流之上,在PipedOutputStream类上有如下的一个方法用于连接管道:

public void connect(PipedInputStream snk)throws IOException

Java IO学习笔记(六):管道流

例子:线程之间用管道流进行通讯

Java IO学习笔记(六):管道流
 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;//管道输出流
 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;//管道输入流
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 send=new Send();
60         Receive receive=new Receive();
61         try {
62             send.getPos().connect(receive.getPis());//连接管道
63         } catch (IOException e) {
64             e.printStackTrace();
65         }
66         new Thread(send).start();//启动线程
67         new Thread(receive).start();//启动线程
68     }
69 }
Java IO学习笔记(六):管道流

相关文章: