3.3管道流
一个线程发送数据到输出管道,另外一个线程从输入管道中读取数据。
工具类:PipedInputStream, PipedOutputStream, PipedReader, PipedWriter
PipedInputStream 通信大小有限制,一个批次默认是 1024 字节。
发送者写满 1024 字节后,接收者开始读取,读取完成一批之后再开始下一批。
WriteData.java
import java.io.PipedOutputStream;
public class WriteData {
public void write(PipedOutputStream outputStream){
try{
System.out.println("Write:" + Thread.currentThread().getName());
for (int i = 0; i < 300; i++) {
String s = "i=" + i;
outputStream.write(s.getBytes());
System.out.println(s);
}
}catch (Exception e){
}
}
}
ReadData.java
import java.io.PipedInputStream;
public class ReadData {
public void read(PipedInputStream inputStream){
try{
System.out.println("Read:" + Thread.currentThread().getName());
byte [] data = new byte[40];
int b = inputStream.read(data);
while(b != -1){
String str = new String(data, 0, b);
System.out.println(str);
b = inputStream.read(data);
}
}catch (Exception e){
}
}
}
ThreadWrite.java
import java.io.PipedOutputStream;
public class ThreadWrite extends Thread{
private WriteData writeData;
private PipedOutputStream outputStream;
public ThreadWrite(PipedOutputStream outputStream, WriteData writeData){
this.outputStream = outputStream;
this.writeData = writeData;
}
@Override
public void run(){
writeData.write(outputStream);
}
}
ThreadRead.java
import java.io.PipedInputStream;
public class ThreadRead extends Thread{
private PipedInputStream inputStream;
private ReadData readData;
public ThreadRead(PipedInputStream inputStream, ReadData readData){
this.inputStream = inputStream;
this.readData = readData;
}
@Override
public void run(){
readData.read(inputStream);
}
}
Run.java
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Run {
public static void main(String[] args) {
WriteData writeData = new WriteData();
ReadData readData = new ReadData();
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
try {
outputStream.connect(inputStream); // connect pipe
}catch (Exception e){
}
ThreadWrite write = new ThreadWrite(outputStream, writeData);
ThreadRead read = new ThreadRead(inputStream, readData);
write.setName("发送者");
read.setName("接收者");
write.start();
read.start();
}
}
刚刚开始的时候,缓存区没有内容,接收者线程阻塞在 int b = inputStream.read(data); 直到整批内容写完。写和读的线程之间通过 b 来同步。
write 时
outputStream.write(str);
read 时
char[] data = new char[40];
String str = new String(data, 0, length);