管道流的处理和线程有关。
管道图解
在java.io包里面如果要想实现线程的通讯管道,使用两个类完成:
PipedOutputStream、PipedInputStream
类的继承关系:
public class PipedOutputStream extends OutputStream
public class PipedInputStream extends InputStream
例:利用管道流实现两个线程之间的通信
class SendThread implements Runnable {
private PipedOutputStream OutputStream = new PipedOutputStream();
@Override
public void run() {
try {
this.OutputStream.write("再见等于再也不见".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public PipedOutputStream getOutput() {
return OutputStream;
}
}
class ReceiveThread implements Runnable {
private PipedInputStream inputStream = new PipedInputStream();
@Override
public void run() {
byte data[] = new byte[1024];
try {
int len = this.inputStream.read(data);
System.out.println("接收数据 " + new String(data, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}
public PipedInputStream getIput() {
return inputStream;
}
}
public class TestDemo_05 {
public static void main(String[] args) throws Exception {
SendThread send = new SendThread();
ReceiveThread receive = new ReceiveThread();
send.getOutput().connect(receive.getIput()); //管道对接
new Thread(send).start();
new Thread(receive).start();
}
}
执行结果:
管道流主要应用在不同线程的通讯处理上。