管道流_PipedInputStream与PipedOutputStream

输入和输出可以直接进行连接,通过结合线程使用(一个线程用于写,另一个用于读,因为管道输入流(读)是要读取管道输出流的数据的,又因为输入流中的read方法是阻塞式的,当两个流在同一个线程中时,输入流的read方法没有数据可以读,就发生阻塞,那么这个线程就挂了)

 1 import java.io.IOException;
 2 import java.io.PipedInputStream;
 3 import java.io.PipedOutputStream;
 4 
 5 public class Test {
 6     public static void main(String[] args) throws IOException {
 7         PipedInputStream input = new PipedInputStream();
 8         PipedOutputStream output = new PipedOutputStream();
 9         
10         input.connect(output);
11         
12         new Thread(new Input(input)).start();
13         new Thread(new Output(output)).start();
14     }
15     
16 }
17 class Input implements Runnable{
18     
19     private PipedInputStream in;
20     Input(PipedInputStream in){
21         this.in = in;
22     }
23     public void run(){
24         
25         try {
26             byte[] buf = new byte[1024];
27             int len = in.read(buf);
28             
29             String s = new String(buf,0,len);
30             
31             System.out.println("s="+s);
32             in.close();
33         } catch (Exception e) {
34             
35         }
36         
37     }
38 }
39 
40 class Output implements Runnable{
41     private PipedOutputStream out;
42     Output(PipedOutputStream out){
43         this.out = out;
44     }
45     public void run(){
46         
47         try {
48             Thread.sleep(5000);
49             out.write("hi,管道来了!".getBytes());
50         } catch (Exception e) {
51             
52         }
53     }
54 }

 

 

转载于:https://www.cnblogs.com/LO-ME/p/3599610.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值