import java.io.*;
class PipedStreamDemo
{
public static void main(String[] args) throws Exception
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
new Thread(new Reader(in)).start();
new Thread(new Writer(out)).start();
}
}
class Reader implements Runnable
{
private PipedInputStream in;
public Reader(PipedInputStream in)
{
this.in = in;
}
public void run()
{
try
{
byte[] buffer = new byte[1024];
int length = 0;
System.out.println("等待读取数据...");
while((length=in.read(buffer))!=-1)
{
System.out.println(new String(buffer,0,length));
}
in.close();
}
catch(Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
}
class Writer implements Runnable
{
private PipedOutputStream out;
public Writer(PipedOutputStream out)
{
this.out = out;
}
public void run()
{
try
{
System.out.println("六秒后开始写入数据...");
Thread.sleep(6000);
out.write("hello PipedStream here.".getBytes());
out.close();
}
catch(Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
}
class PipedStreamDemo
{
public static void main(String[] args) throws Exception
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
new Thread(new Reader(in)).start();
new Thread(new Writer(out)).start();
}
}
class Reader implements Runnable
{
private PipedInputStream in;
public Reader(PipedInputStream in)
{
this.in = in;
}
public void run()
{
try
{
byte[] buffer = new byte[1024];
int length = 0;
System.out.println("等待读取数据...");
while((length=in.read(buffer))!=-1)
{
System.out.println(new String(buffer,0,length));
}
in.close();
}
catch(Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
}
class Writer implements Runnable
{
private PipedOutputStream out;
public Writer(PipedOutputStream out)
{
this.out = out;
}
public void run()
{
try
{
System.out.println("六秒后开始写入数据...");
Thread.sleep(6000);
out.write("hello PipedStream here.".getBytes());
out.close();
}
catch(Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
}