A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Kikyou2014 中级黑马   /  2014-11-5 21:33  /  916 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.io.*;
  2. class Read implements Runnable
  3. {
  4.         private PipedInputStream pis;
  5.         public Read(PipedInputStream pis)
  6.         {
  7.                 this.pis=pis;
  8.         }
  9.         public void run()
  10.         {
  11.                 byte[] buf=new byte[1024];
  12.                 int len=0;
  13.                 System.out.println("开始读取数据!");
  14.                 try
  15.                 {
  16.                         len=pis.read(buf);
  17.                 }
  18.                 catch (IOException e)
  19.                 {
  20.                         throw new RuntimeException("读取数据失败!");
  21.                 }
  22.                 System.out.println("数据读取完毕!");
  23.                 System.out.println(new String(buf,0,len));
  24.         }
  25. }
  26. class Write implements Runnable
  27. {
  28.         private PipedOutputStream pos;
  29.         public Write(PipedOutputStream pos)
  30.         {
  31.                 this.pos=pos;
  32.         }
  33.         public void run()
  34.         {
  35.                 System.out.println("5秒后写入数据,进入阻塞!");
  36.                 try
  37.                 {
  38.                         Thread.sleep(5000);
  39.                 }
  40.                 catch (InterruptedException e)
  41.                 {
  42.                         e.getMessage();
  43.                 }
  44.                 try
  45.                 {
  46.                         pos.write("hehehe".getBytes());
  47.                 }
  48.                 catch (IOException e)
  49.                 {
  50.                         throw new RuntimeException("数据写出失败!");
  51.                 }
  52.                 System.out.println("数据写入完毕,解除阻塞!");
  53.         }
  54. }
  55. class PipedStreamDemo
  56. {
  57.         public static void main(String[] args)
  58.         {
  59.                 PipedInputStream pis=null;
  60.                 PipedOutputStream pos=null;
  61.                 try
  62.                 {
  63.                         pis=new PipedInputStream();
  64.                         pos=new PipedOutputStream();
  65.                         pos.connect(pis);
  66.                 }
  67.                 catch (IOException e)
  68.                 {
  69.                         throw new RuntimeException("管道连接失败!");
  70.                 }
  71.                 new Thread(new Write(pos)).start();
  72.                 new Thread(new Read(pis)).start();
  73.         }
  74. }
复制代码
到底是管道输出到输入,还是输入到输出

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马