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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© huazi 中级黑马   /  2014-7-28 12:10  /  719 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 huazi 于 2014-7-28 12:22 编辑
  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.                 new Thread(r).start();
  59.                 new Thread(w).start();
  60.         }
复制代码
/**我的问题是:
*Write类中的out.write("piped lai la".getBytes());这是一个字节数组
*这个数组中的数据是怎么存入到Read类中byte[] buf = new byte[1024];这个数组里面去的?
*这两者之间在内存里面是怎样的一个情况?求解,谢谢
*/

2 个回复

倒序浏览
来个解答的,谢谢
回复 使用道具 举报
视频说清楚了哟。。。read 是一个阻塞方法。。如果没有读到数据 线程就卡在那里等。。当out.write("piped lai la".getBytes()) 写入数据以后。。 read 线程就又活了。 然后将数据读到了 字节数组中去
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马