管道提供線程間直接數據傳輸通道,無需臨時文件。兩大核心類:
連接方式:
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out); // 綁定
或反向:out.connect(in)。連接後即可像操作文件流一樣讀寫。
架構:主線程 → yThread (x→y) → zThread (y→z) → 主線程顯示
public class PipeApp {
public static void main(String[] args) throws IOException {
FileInputStream fileIn = new FileInputStream("input.txt");
InputStream yPipe = changeToY(fileIn); // 啟動 yThread
InputStream zPipe = changeToZ(yPipe); // 啟動 zThread
DataInputStream dis = new DataInputStream(zPipe);
String line;
while ((line = dis.readLine()) != null) {
System.out.println(line);
}
dis.close();
}
InputStream changeToY(InputStream in) throws IOException {
DataInputStream din = new DataInputStream(in);
PipedOutputStream pOut = new PipedOutputStream();
PipedInputStream pIn = new PipedInputStream(pOut);
PrintStream ps = new PrintStream(pOut);
new YThread(din, ps).start();
return pIn;
}
InputStream changeToZ(InputStream in) throws IOException {
DataInputStream din = new DataInputStream(in);
PipedOutputStream pOut = new PipedOutputStream();
PipedInputStream pIn = new PipedInputStream(pOut);
PrintStream ps = new PrintStream(pOut);
new ZThread(din, ps).start();
return pIn;
}
}
class YThread extends Thread {
private DataInputStream in;
private PrintStream out;
YThread(DataInputStream in, PrintStream out) {
this.in = in; this.out = out;
}
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
out.println(line.replace('x', 'y'));
out.flush(); // 確保數據進入管道
}
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
// ZThread 同理,replace('y','z')
flush() 強制緩衝區寫入,避免數據滯留