本文部分摘自《Java 併發編程的藝術》java
管道輸入 / 輸出流和普通的文件輸入 / 輸出流或者網絡輸入 / 輸出流不一樣之處在於,它主要用於線程之間的數據傳輸,而傳輸媒介爲內存編程
管道輸入 / 輸出流主要包括以下四種具體實現:網絡
前兩種面向字節,後兩種面向字符併發
下面的例子中,main 線程經過 PipedWriter 向 printThread 線程寫入數據,printThread 線程經過 PipedReader 將讀取數據並打印ide
public class Piped { public static void main(String[] args) throws IOException { PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(); // 將輸入流和輸出流進行鏈接,不然在使用時會拋出 IOException out.connect(in); Thread printThread = new Thread(new Print(in), "PrintThread"); printThread.start(); int receive = 0; try { while ((receive = System.in.read()) != -1) { out.write(receive); } } finally { out.close(); } } static class Print implements Runnable { private PipedReader in; public Print(PipedReader in) { this.in = in; } @Override public void run() { int receive = 0; try { while ((receive = in.read()) != -1) { System.out.print((char) receive); } } catch (IOException e) { e.printStackTrace(); } } } }
運行結果以下this