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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Gaara33 中级黑马   /  2014-6-12 12:44  /  670 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Gaara33 于 2014-6-18 21:25 编辑
  1. import java.io.*;
  2. class Read implements Runnable
  3. {
  4.         private PipedInputStream in;
  5.         Read (PipedInputStream in)
  6.         {
  7.                 this.in = in;
  8.         }
  9.         public void run()
  10.         {
  11.                 try
  12.                 {

  13.                         byte [] buf = new byte[1024];
  14.                         System.out.println("读取前。。没有数据,阻塞");
  15.                         int len = in.read(buf);
  16.                         System.out.println("读到数据。。阻塞结束");
  17.                         String s = new String(buf,0,len);
  18.                         System.out.println(s);
  19.                         in.close();
  20.                 }
  21.                 catch (IOException e)
  22.                 {
  23.                         throw new RuntimeException("管道读取流失败");
  24.                 }
  25.         }
  26. }
  27. class Write implements Runnable
  28. {
  29.         private PipedOutputStream out;
  30.         Write(PipedOutputStream out)
  31.         {
  32.                 this.out = out;

  33.         }
  34.         public void run()
  35.         {
  36.                 try
  37.                 {
  38.                         System.out.println("开始写入数据,等待6秒。。。");
  39.                         Thread.sleep(6000);
  40.                         out.write("piped lai la".getBytes());
  41.                         out.close();
  42.                 }
  43.                 catch (Exception e)
  44.                 {
  45.                         throw new RuntimeException("管道输出流失败");
  46.                 }
  47.         }
  48. }
  49. class PipedStreamDemo
  50. {
  51.         public static void main(String[] args) throws IOException
  52.         {
  53.                 PipedInputStream in = new PipedInputStream();
  54.                 PipedOutputStream out = new PipedOutputStream();
  55.                 in.connect(out);

  56.                 Read r = new Read(in);
  57.                 Write w = new Write(out);
  58.                
  59.                 new Thread(r).start();
  60.                 new Thread(w).start();

  61. //                in.close();
  62. //                out.close();
  63.         }
  64. }
复制代码



PipedInputStream
PipedOutputStream
这两个流不是也需要关闭吗,在看视频的时候,没有说要关闭,我试着关闭了一下,就出问题了,求大神指点。。。

0 个回复

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