一、PipedInputStream:管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。
步骤:
输出流一端
1、PipedOutputStream pos = null;
pos = new PipedOutputStream();
2、调用write方法写入输出流
3、关闭输出流
二、PipedOutputStream:可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。
步骤:
输入流一端
1、PipedInputStream pis = null;
pis = new PipedInputStream();
2、调用read方法读取输出流传递过来的信息
3、关闭输入流
三、测试一端
1、启动两个线程,分别获取发送者和接受者的输出、输入流
2、连接输入流到输出流
3、启动线程
import java.io.*;
public class PipedDemo02 {
public static void main(String[] args) throws IOException {
SendThread st = new SendThread();
ReceiveThread rt = new ReceiveThread();
PipedOutputStream out = st.getOut();
PipedInputStream in = rt.getIn();
out.connect(in);
Thread send = new Thread(st);
Thread receive = new Thread(rt);
send.start();
receive.start();
}
}
class SendThread implements Runnable{
PipedOutputStream pos = null;
public SendThread(){
pos = new PipedOutputStream();
}
public PipedOutputStream getOut(){
return this.pos;
}
@Override
public void run() {
String str = "Hello,World";
try {
pos.write(str.getBytes());
pos.close();
} catch (IOException e) {
}
System.out.println("发送的内容:"+str);
}
}
class ReceiveThread implements Runnable{
PipedInputStream pis = null;
public ReceiveThread(){
pis = new PipedInputStream();
}
public PipedInputStream getIn(){
return this.pis;
}
@Override
public void run() {
byte b[] = new byte[1024] ;
int len = 0 ;
try{
len = pis.read(b) ;
pis.close() ;
}
catch (Exception e){
}
System.out.println("接受的内容:"+new String(b,0,len));
}
}
发送的内容:Hello,World
接受的内容:Hello,World