首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2EE

Java 管道流實現線程間通訊:PipedInputStream 與 PipedOutputStream 實戰

     編輯:J2EE

管道流核心概念

管道提供線程間直接數據傳輸通道,無需臨時文件。兩大核心類:

  • PipedOutputStream:寫入端,生產者線程向管道輸出數據
  • PipedInputStream:讀取端,消費者線程從管道讀取數據

連接方式:

PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out); // 綁定

或反向:out.connect(in)。連接後即可像操作文件流一樣讀寫。

完整實戰:三線程管道鏈 (x→y→z)

架構:主線程 → yThread (x→y) → zThread (y→z) → 主線程顯示

主程序 (PipeApp)

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;
    }
}

轉換線程 (YThread / ZThread)

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() 強制緩衝區寫入,避免數據滯留
  • 異常處理與資源關閉不可省略
  • 適用於生產者-消費者模式的流式數據處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved