Java语言中提供了各种各样的输入输出流Stream,使我们能够很方便地对数据进行操作,其中管道流(pipeStream)是一种特殊的流,用于在不同线程间之间传送数据。一个线程发送数据到输出管道,另一个线程从输入管道中读数据。通过使用管道,实现不同线程间的通信,而无须借助类似于临时文件之类的东西。
在Java的JDK中提供了4个类来使线程间可以相互通信:
1)PipedInputSteam和PipedOutputStream
2)PipedReader和PipedWriter
PipedReader和PipedWriter在管道间传送字符流,下面以其为例说明使用。
ThreadWrite类,发送数据的线程。
import java.io.IOException;
import java.io.PipedWriter;
public class ThreadWrite extends Thread{
private PipedWriter out;
public ThreadWrite(PipedWriter out){
super();
this.out = out;
}
@Override
public void run(){
try{
System.out.println("write:");
for(int i=0;i<300;i++){
String outData = ""+(i+1);
out.write(outData);
System.out.print(outData);
}
System.out.println();
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
ThreadRead类,读取数据的线程。
import java.io.IOException;
import java.io.PipedReader;
public class ThreadRead extends Thread{
private PipedReader input;
public ThreadRead(PipedReader input){
super();
this.input = input;
}
@Override
public void run(){
try{
System.out.println("read:");
char[] byteArray = new char[100];
int readLength = input.read(byteArray);
while (readLength!=-1){
String newData = new String(byteArray,0,readLength);
System.out.print(newData);
readLength = input.read(byteArray);
}
System.out.println();
input.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
测试类:
import java.io.PipedReader;
import java.io.PipedWriter;
public class RunTest {
public static void main(String[] args){
try{
PipedReader pipedReader = new PipedReader();
PipedWriter pipedWriter = new PipedWriter();
//inputStream.connect(outputStream);
pipedWriter.connect(pipedReader); //将pipedWriter和pipeRead通过connect相连
ThreadRead threadRead = new ThreadRead(pipedReader); //启动读线程
threadRead.start();
Thread.sleep(2000);
ThreadWrite threadWrite = new ThreadWrite(pipedWriter); //启动写线程
threadWrite.start();
}catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
程序输入如下所示:
参考《Java多线程编程核心技术》