package demo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedIODemo {
public static void main(String[] args) {
//管道流
SendThread send = new SendThread();
ReceiveThread receive = new ReceiveThread();
// 连接两个管道
try {
send.getOutput().connect(receive.getInput());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(send, "send线程").start();
;
new Thread(receive, "receive线程").start();
}
}
class SendThread implements Runnable {
private PipedOutputStream output;
public SendThread() {
this.output = new PipedOutputStream();
}
public PipedOutputStream getOutput() {
return this.output;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
this.output.write(("{第"+i+"次消息内容:"+" ,发送方: " + Thread.currentThread().getName()+ "}\n").getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
this.output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ReceiveThread implements Runnable {
private PipedInputStream input;
public ReceiveThread() {
this.input = new PipedInputStream();
}
public PipedInputStream getInput() {
return input;
}
public void run() {
byte[] buf = new byte[256];
int len = 0;
// 所有收到的数据保存到内存流
ByteArrayOutputStream mem = new ByteArrayOutputStream();
try {
while ((len = input.read(buf)) != -1) {
mem.write(buf, 0, len); //// 所有收到的数据保存到内存流
}
System.out.println(Thread.currentThread().getName()+"收到消息:" + new String(mem.toByteArray()));
mem.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
this.input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}