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();
}
}
刚写了这个,但是管道流失败,怎么办?作者: blue_sky 时间: 2014-6-30 09:54
管道流中 PipedInputStream 和 PipedOutputStream要进行连接才能使用;试想一下,这有一个输入流管道和一个输出流管道。却没有将两个管道连接起来,也是不行的。
所以在主函数下:
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
之后,添加:
in.connect(out);
即可。