IO:管道流(线程通信流)

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

public void connect(PipedInputStream snk)throws IOException

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

复制代码
 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 }
复制代码

 

转载于:https://www.cnblogs.com/olddriver123/p/8257891.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值