本章,我們學習PipedReader和PipedWriter。它們和“PipedInputStream和PipedOutputStream”一樣,都可以用於管道通訊。
PipedWriter 是字元管道輸出資料流,它繼承於Writer。
PipedReader 是字元管道輸入資料流,它繼承於Writer。
PipedWriter和PipedReader的作用是可以通過管道進行線程間的通訊。在使用管道通訊時,必須將PipedWriter和PipedReader配套使用。
PipedWriter和PipedReader源碼分析
1. PipedWriter 源碼(基於jdk1.7.40)
package java.io; public class PipedWriter extends Writer { // 與PipedWriter通訊的PipedReader對象 private PipedReader sink; // PipedWriter的關閉標記 private boolean closed = false; // 建構函式,指定配對的PipedReader public PipedWriter(PipedReader snk) throws IOException { connect(snk); } // 建構函式 public PipedWriter() { } // 將“PipedWriter” 和 “PipedReader”串連。 public synchronized void connect(PipedReader snk) throws IOException { if (snk == null) { throw new NullPointerException(); } else if (sink != null || snk.connected) { throw new IOException("Already connected"); } else if (snk.closedByReader || closed) { throw new IOException("Pipe closed"); } sink = snk; snk.in = -1; snk.out = 0; // 設定“PipedReader”和“PipedWriter”為已串連狀態 // connected是PipedReader中定義的,用於表示“PipedReader和PipedWriter”是否已經串連 snk.connected = true; } // 將一個字元c寫入“PipedWriter”中。 // 將c寫入“PipedWriter”之後,它會將c傳輸給“PipedReader” public void write(int c) throws IOException { if (sink == null) { throw new IOException("Pipe not connected"); } sink.receive(c); } // 將字元數組b寫入“PipedWriter”中。 // 將數組b寫入“PipedWriter”之後,它會將其傳輸給“PipedReader” public void write(char cbuf[], int off, int len) throws IOException { if (sink == null) { throw new IOException("Pipe not connected"); } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } sink.receive(cbuf, off, len); } // 清空“PipedWriter”。 // 這裡會調用“PipedReader”的notifyAll(); // 目的是讓“PipedReader”放棄對當前資源的佔有,讓其它的等待線程(等待讀取PipedWriter的線程)讀取“PipedWriter”的值。 public synchronized void flush() throws IOException { if (sink != null) { if (sink.closedByReader || closed) { throw new IOException("Pipe closed"); } synchronized (sink) { sink.notifyAll(); } } } // 關閉“PipedWriter”。 // 關閉之後,會調用receivedLast()通知“PipedReader”它已經關閉。 public void close() throws IOException { closed = true; if (sink != null) { sink.receivedLast(); } }}