zoukankan      html  css  js  c++  java
  • 管道流_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 }
  • 相关阅读:
    Knative Serving 进阶: Knative Serving SDK 开发实践
    从求生存到修体系,我在阿里找到了技术人的成长模式
    K8s 学习者绝对不能错过的最全知识图谱(内含 56个知识点链接)
    P1197 [JSOI2008]星球大战
    P1311 选择客栈
    P2822 组合数问题
    贪心 加工生产调度
    P3375 【模板】KMP字符串匹配
    P1025 数的划分
    P1019 单词接龙
  • 原文地址:https://www.cnblogs.com/LO-ME/p/3599610.html
Copyright © 2011-2022 走看看