这些流平常都没怎么接触过,这里用代码测试记录一下
//管道流:
/*让多线程可以通过管道进行线程间的通讯。必须将PipedOutputStream和PipedInputStream配套使用。
大致的流程是:我们在线程A中向PipedOutputStream中写入数据,
这些数据会自动的发送到与PipedOutputStream对应的PipedInputStream中,
进而存储在PipedInputStream的缓冲中;
此时,线程B通过读取PipedInputStream中的数据。就可以实现,线程A和线程B的通信。*/
public class IOTest {
public static void main(String[] args) throws IOException {
Send send = new Send();
Recive recive = new Recive();
try {
// 管道连接
send.getOut().connect(recive.getInput());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread());
new Thread(send).start();
new Thread(recive).start();
}
}
class Send implements Runnable {
private PipedOutputStream out = null;
public Send() {
out = new PipedOutputStream();
}
public PipedOutputStream getOut() {
return this.out;
}
public void run() {
String message = "hello , Rollen";
try {
out.write(message.getBytes());
System.out.println(Thread.currentThread() + "发送数据成功");
} catch (Exception e) {
e.printStackTrace();
}
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 接受消息类
*/
class Recive implements Runnable {
private PipedInputStream input = null;
public Recive() {
this.input = new PipedInputStream();
}
public PipedInputStream getInput() {
return this.input;
}
public void run() {
byte[] b = new byte[1000];
int len = 0;
try {
len = this.input.read(b);
} catch (Exception e) {
e.printStackTrace();
}
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "接受的内容为 " + (new String(b, 0, len)));
}
}