黑马程序员技术交流社区
标题:
管道流的一个问题
[打印本页]
作者:
zhaojian
时间:
2014-6-11 17:00
标题:
管道流的一个问题
本帖最后由 zhaojian 于 2014-6-12 13:56 编辑
/*编写两个线程子类,分别用来创建管道输出流和管道输入流,
其中管道输出流向管道发送5个0~20之间的随机整数;
管道输入流接收管道中传过来的5个随机整数,并求他们的和。
编写Java应用程序测试管道流的数据传送。*/
import java.io.*;
class PipedText
{
public static void main(String[] args) throws Exception
{
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream();
pos.connect(pis);
PipedInput pi=new PipedInput(pis);
PipedOutput po=new PipedOutput(pos);
new Thread(pi).start();
new Thread(po).start();
}
}
class PipedInput implements Runnable
{
private PipedInputStream pis;
PipedInput(PipedInputStream pis)
{
this.pis=pis;
}
//管道输入流接收发送过来的数,并打印它们的和
public void run()
{
try
{
byte [] buf=new byte[100];
int len=0;
int sum=0;
while((len=pis.read(buf))!=-1)
{
String s=new String(buf,0,len);
//System.out.println(s+"--s");
int i=Integer.parseInt(s);
sum+=i;
}
System.out.println(sum);
pis.close();
}
catch (IOException io)
{
throw new RuntimeException();
}
}
}
class PipedOutput implements Runnable
{
private PipedOutputStream pos;
PipedOutput(PipedOutputStream pos)
{
this.pos=pos;
}
//管道输出流发送5个0-20的随机数
public void run()
{
try
{
for (int x=0;x<5 ;x++ )
{
int i=(int)(Math.random()*20);
//System.out.println(i+"....i");
String s=i+"";
pos.write(s.getBytes());
pos.flush();
}
pos.close();
}
catch (IOException io)
{
throw new RuntimeException();
}
}
}
复制代码
最后打印结果总是不对,如果不注释掉了中间的两个打印语句,就能打印出正确结果,应该数据都存到缓冲区里了,然后一次都读出来了,有什么解决办法只打印最后结果,能不能再帮忙优化一下代码。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2