import java.io.*;
public class PiperTest {
public static void main(String[] args) throws IOException {
PiperOutputTest send = new PiperOutputTest();
ReceiveThread receiveThread = new ReceiveThread();
send.getOutput().connect(receiveThread.getInput());//进行管道连接
new Thread(send,"消息发送线程").start();
new Thread(receiveThread,"消息接收线程").start();
}
}
class PiperOutputTest implements Runnable{
private PipedOutputStream output;
public PiperOutputTest() {
this.output = new PipedOutputStream(); //实例化管道输出流
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try{//输出消息编辑
this.output.write(("【第" + (i+1) + "次信息发送 -" + Thread.currentThread().getName() + " 】www.baidu.com\n").getBytes());
Thread.sleep(1000);
}catch (Exception e) {
System.out.print(e.getMessage());
}
}
try{
this.output.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public PipedOutputStream getOutput(){
return output;
}
}
class ReceiveThread implements Runnable{
private PipedInputStream input;
public ReceiveThread() {
// TODO Auto-generated constructor stub
this.input = new PipedInputStream(); //实例化输出管道流
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
byte data [] = new byte [1024];
try{
int len = this.input.read(data) ;
System.out.print("{"+Thread.currentThread().getName() + "接收消息}\n" + new String(data,0,len));//打印机接收的消息
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
try {
this.input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PipedInputStream getInput() {
return input;
}
}