Java通過管道進行程序間通訊
阿新 • • 發佈:2019-02-18
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多執行緒程式設計核心技術》