Java管道流

管道流的主要作用可以用于两个线程之间的通信,有管道输出流 PipeOutputStream和管道输入流 PipeInputStream。然后通过connect将两个管道连接起来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
 
class Send implements Runnable{
    private PipedOutputStream pos = null;
     
    public Send() {
        // TODO Auto-generated constructor stub
        pos = new PipedOutputStream();
    }
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        String str = "Hello world!";
        try {
            pos.write(str.getBytes());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
         
        try {
            pos.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
     
    public PipedOutputStream getPos() {
        return pos;
    }  
}
 
class Receive implements Runnable{
    private PipedInputStream pis = null;
     
    public Receive() {
        // TODO Auto-generated constructor stub
        pis = new PipedInputStream();
    }
     
    public PipedInputStream getPis() {
        return pis;
    }
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        byte[] b = new byte[1024];
        int len = 0;
        try {
            len = pis.read(b);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
         
        try {
            pis.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
         
        System.out.println(new String(b, 0, len));
    }  
     
}
 
public class PipeDemo01 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Send s = new Send();
        Receive r = new Receive();
        try {
            s.getPos().connect(r.getPis());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
         
        new Thread(s).start();
        new Thread(r).start();
    }
 
}

  

 

posted on   aituming  阅读(374)  评论(0编辑  收藏  举报

统计

点击右上角即可分享
微信分享提示