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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 奔跑的二叉树 中级黑马   /  2013-9-20 10:26  /  804 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 奔跑的二叉树 于 2013-9-20 20:54 编辑

先贴代码
  1. package cn.os.du;
  2. import java.io.*;
  3. class Read implements Runnable
  4. {
  5.         private PipedInputStream in;
  6.         Read(PipedInputStream in)
  7.         {
  8.                 this.in=in;
  9.         }
  10.         public void run()
  11.         {
  12.                 try
  13.                 {
  14.                         byte[] buf =new byte[1024];
  15.                         System.out.println("读取前 ..没有数据阻塞");
  16.                         int len=in.read(buf);
  17.                         System.out.println("读到数据 ..阻塞结束");
  18.                         String s=new String(buf,0,len);
  19.                         System.out.println(s);
  20.                         in.close();
  21.                 }
  22.                 catch(IOException e)
  23.                 {
  24.                         throw new RuntimeException("管道读取流失败");
  25.                 }
  26.         }
  27. }

  28. class Write implements Runnable
  29. {
  30.         private PipedOutputStream out;
  31.         Write(PipedOutputStream out)
  32.         {
  33.                 this.out=out;
  34.         }
  35.         public void run()
  36.         {
  37.                 try
  38.                 {
  39.                         System.out.println("开始写入数据------------------------,等待1秒后。");
  40.                         Thread.sleep(500);
  41.                         out.write("piped lai la".getBytes());
  42.                         out.close();
  43.                 }
  44.                 catch(IOException e)
  45.                 {
  46.                         throw new RuntimeException("管道输出流失败");
  47.                 } catch (Exception e) {
  48.                         // TODO Auto-generated catch block
  49.                         e.printStackTrace();
  50.                 }
  51.         }
  52. }
  53. public class pipedStream {

  54.         public static void main(String[] args) throws IOException {
  55.                 PipedInputStream in=new PipedInputStream();
  56.                 PipedOutputStream out=new PipedOutputStream();
  57.                 in.connect(out);//连接管道 输入输出流
  58.                
  59.                 Read r=new Read(in);
  60.                 Write w=new Write(out);
  61.                 new Thread(r).start();
  62.                 new Thread(w).start();
  63.                

  64.         }

  65. }
复制代码
为什么我执行的结果每次都一样,应该输入输出流都有可能先执行的啊,试了N遍都一样

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

2 个回复

倒序浏览
我运行了一下,你先开启写入数据线程,写入就先执行了,就是把最后两句代码调换.可能是线程运行太快,如果数据太少,如果数据多的话,看的就明显了

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

回复 使用道具 举报
我试了三次,输入输出流有交替先运行的情况
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马