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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© itisdream 中级黑马   /  2014-6-29 09:17  /  891 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.io.*;

class Read implements Runnable
{
        private PipedInputStream in;
        Read(PipedInputStream in)
        {
                this.in = in ;
        }
        public void run()
        {
                try
                {
                        byte []buf = new byte[1024];
                        int len = in.read(buf);
                        String s = new String(buf,0,len);
                        System.out.println(s);
                        in.close();
                }
                catch(IOException e){throw new RuntimeException("失败");}
        }
}
class Write implements Runnable
{
        private PipedOutputStream out;
        Write(PipedOutputStream out)
        {
                this.out = out ;
        }
        public void run()
        {               
                try
                {
                        Thread.sleep(6000);
                        out.write("guandaolaile...".getBytes());
                        out.close();
                }
                catch(IOException e){throw new RuntimeException("失败");} catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}
public class PipedStreamDemo
{
        public static void main(String []args)throws Exception
        {
                PipedInputStream in = new PipedInputStream();
                PipedOutputStream out = new PipedOutputStream();
                Read r =new Read(in);
                Write w = new Write(out);
                new Thread(r).start();
                new Thread(w).start();
        }
}
刚写了这个,但是管道流失败,怎么办?

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

1 个回复

倒序浏览
管道流中 PipedInputStream 和 PipedOutputStream要进行连接才能使用;试想一下,这有一个输入流管道和一个输出流管道。却没有将两个管道连接起来,也是不行的。
所以在主函数下:
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
之后,添加:
     in.connect(out);
即可。

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马