1 字节流管道
通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。 如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。
1.1 PipedInputStream
1.2 PipedOutputStream
1.3 使用字节流管道进行线程间的通信
WriteData.java
package pipe;
import java.io.IOException;
import java.io.PipedOutputStream;
public class WriteData extends Thread {
private PipedOutputStream pipedOS;
private String data;
public WriteData(PipedOutputStream pipedOS, String data) {
super("Writer");
this.pipedOS = pipedOS;
this.data = data;
}
@Override
public void run() {
super.run();
try {
String tmp;
for (int i = 0; i < 6; i++) {
tmp = data + i + " ";
System.out.println(Thread.currentThread().getName() + " writed " + tmp + " into the pipe.");
pipedOS.write(tmp.getBytes());
}
pipedOS.flush();
pipedOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ReadData.java
package pipe;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class ReadData extends Thread {
private PipedInputStream pipedIS;
public ReadData(PipedInputStream pipedIS) {
super("Reader");
this.pipedIS = pipedIS;
}
@Override
public void run() {
super.run();
try {
System.out.println(Thread.currentThread().getName() + " begined reading the data from the pipe.");
byte[] bytes = new byte[20];
int readLen = -1;
readLen = pipedIS.read(bytes);
while (readLen != -1) {
String s = new String(bytes, 0, readLen);
System.out.println(s);
try {
readLen = pipedIS.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println();
pipedIS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
PipedInputStream pipedInputStream = new PipedInputStream();
PipedOutputStream pipedOutputStream = new PipedOutputStream();
try {
pipedInputStream.connect(pipedOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
WriteData writeData = new WriteData(pipedOutputStream, "ABC");
ReadData readData = new ReadData(pipedInputStream);
writeData.start();
readData.start();
}
}
输出
Reader begined reading the data from the pipe.
Writer writed ABC0 into the pipe.
Writer writed ABC1 into the pipe.
Writer writed ABC2 into the pipe.
Writer writed ABC3 into the pipe.
Writer writed ABC4 into the pipe.
Writer writed ABC5 into the pipe.
ABC0 ABC1 ABC2 ABC3
ABC4 ABC5
2 字符流通道
2.1 PipedReader
2.2 PipedWriter
由于管道通信的原理是一样的,不过一个是处理字节流,一个是处理字符流,区别不大,所以这里代码就不再编写了。