072.JAVA输入输出_管道流实现线程通信


博主的 Github 地址


1. 管道流

  • 管道流用于实现线程之间的数据交互, 但通常来说这个并不使用.
  • 管道流根据输入输出和字节字符类型一共有四种:
    • PipedInputStream
    • PipedOutputStream
    • PipedReader
    • PipedWriter

1.1. 操作实例

  • 定义 A 线程

    //A线程发送数据给B线程
    class AThread extends Thread{
      private PipedOutputstream out = new PipedOutputStream();
      //定义方法用以返回线程的管道输出流
      public PipedOutputStream getOut(){
          return out;
      }
      public void run(){
          try {
              //在管道流中写入26个字母
              for(int i = 65; i < 65 + 26; i++) out.write(i);
              out.c1ose() ;
          }catch(IOException e){
              e.printstackTrace();
          }
      }
    }
  • 定义 B 线程

    //B线程接受A线程发送的数据
    class BThread extends Thread{
      PipedInputStream in = null;
      public BThread (AThread aThread) throws Exception{
          //获取并包装A线程的管道输出流
          in = new PipedInputStream(aThread.getOut());
      }
      public void run(){
          int len= -1;
          try{
              //打印从A线程的管道流中获取的内容
              while((len = in.read()) != -1){
                  System.out.println((char)len) ;
              }
              in.close();
          } catch(IOException e){
              e.printstackTrace() ;
          }
      }
    }
  • 主方法

    public class PipedStreamDemo{
      public static void main(String[] args){
          AThread a = new AThread();
          BThread b = new BThread(a);
    
          //线程开始后, 最终控制台会输出26个字母
          a.start();
          b.start();
      }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值