java io系列20之 PipedReader和PipedWriter



本章,我們學習PipedReader和PipedWriter。它們和“PipedInputStreamPipedOutputStream”一樣,都可以用於管道通信。

PipedWriter 是字符管道輸出流,它繼承於Writer。
PipedReader 是字符管道輸入流,它繼承於Writer。
PipedWriter和PipedReader的作用是可以通過管道進行線程間的通訊。在使用管道通信時,必須將PipedWriter和PipedReader配套使用。

轉載請注明出處:http://www.cnblogs.com/skywang12345/p/io_20.html

更多內容請參考:java io系列01之 "目錄"

PipedWriter和PipedReader源碼分析

1. PipedWriter 源碼(基於jdk1.7.40)

 1 package java.io;
 2 
 3 public class PipedWriter extends Writer {
 4 
 5     // 與PipedWriter通信的PipedReader對象
 6     private PipedReader sink;
 7 
 8     // PipedWriter的關閉標記
 9     private boolean closed = false;
10 
11     // 構造函數,指定配對的PipedReader
12     public PipedWriter(PipedReader snk)  throws IOException {
13         connect(snk);
14     }
15 
16     // 構造函數
17     public PipedWriter() {
18     }
19 
20     // 將“PipedWriter” 和 “PipedReader”連接。
21     public synchronized void connect(PipedReader snk) throws IOException {
22         if (snk == null) {
23             throw new NullPointerException();
24         } else if (sink != null || snk.connected) {
25             throw new IOException("Already connected");
26         } else if (snk.closedByReader || closed) {
27             throw new IOException("Pipe closed");
28         }
29 
30         sink = snk;
31         snk.in = -1;
32         snk.out = 0;
33         // 設置“PipedReader”和“PipedWriter”為已連接狀態
34         // connected是PipedReader中定義的,用於表示“PipedReader和PipedWriter”是否已經連接
35         snk.connected = true;
36     }
37 
38     // 將一個字符c寫入“PipedWriter”中。
39     // 將c寫入“PipedWriter”之后,它會將c傳輸給“PipedReader”
40     public void write(int c)  throws IOException {
41         if (sink == null) {
42             throw new IOException("Pipe not connected");
43         }
44         sink.receive(c);
45     }
46 
47     // 將字符數組b寫入“PipedWriter”中。
48     // 將數組b寫入“PipedWriter”之后,它會將其傳輸給“PipedReader”
49     public void write(char cbuf[], int off, int len) throws IOException {
50         if (sink == null) {
51             throw new IOException("Pipe not connected");
52         } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < 0) {
53             throw new IndexOutOfBoundsException();
54         }
55         sink.receive(cbuf, off, len);
56     }
57 
58     // 清空“PipedWriter”。
59     // 這里會調用“PipedReader”的notifyAll();
60     // 目的是讓“PipedReader”放棄對當前資源的占有,讓其它的等待線程(等待讀取PipedWriter的線程)讀取“PipedWriter”的值。
61     public synchronized void flush() throws IOException {
62         if (sink != null) {
63             if (sink.closedByReader || closed) {
64                 throw new IOException("Pipe closed");
65             }
66             synchronized (sink) {
67                 sink.notifyAll();
68             }
69         }
70     }
71 
72     // 關閉“PipedWriter”。
73     // 關閉之后,會調用receivedLast()通知“PipedReader”它已經關閉。
74     public void close()  throws IOException {
75         closed = true;
76         if (sink != null) {
77             sink.receivedLast();
78         }
79     }
80 }
View Code

2. PipedReader 源碼(基於jdk1.7.40)

  1 package java.io;
  2 
  3 public class PipedReader extends Reader {
  4     // “PipedWriter”是否關閉的標記
  5     boolean closedByWriter = false;
  6     // “PipedReader”是否關閉的標記
  7     boolean closedByReader = false;
  8     // “PipedReader”與“PipedWriter”是否連接的標記
  9     // 它在PipedWriter的connect()連接函數中被設置為true
 10     boolean connected = false;
 11 
 12     Thread readSide;    // 讀取“管道”數據的線程
 13     Thread writeSide;    // 向“管道”寫入數據的線程
 14 
 15     // “管道”的默認大小
 16     private static final int DEFAULT_PIPE_SIZE = 1024;
 17 
 18     // 緩沖區
 19     char buffer[];
 20 
 21     //下一個寫入字符的位置。in==out代表滿,說明“寫入的數據”全部被讀取了。
 22     int in = -1;
 23     //下一個讀取字符的位置。in==out代表滿,說明“寫入的數據”全部被讀取了。
 24     int out = 0;
 25 
 26     // 構造函數:指定與“PipedReader”關聯的“PipedWriter”
 27     public PipedReader(PipedWriter src) throws IOException {
 28         this(src, DEFAULT_PIPE_SIZE);
 29     }
 30 
 31     // 構造函數:指定與“PipedReader”關聯的“PipedWriter”,以及“緩沖區大小”
 32     public PipedReader(PipedWriter src, int pipeSize) throws IOException {
 33         initPipe(pipeSize);
 34         connect(src);
 35     }
 36 
 37     // 構造函數:默認緩沖區大小是1024字符
 38     public PipedReader() {
 39         initPipe(DEFAULT_PIPE_SIZE);
 40     }
 41 
 42     // 構造函數:指定緩沖區大小是pipeSize
 43     public PipedReader(int pipeSize) {
 44         initPipe(pipeSize);
 45     }
 46 
 47     // 初始化“管道”:新建緩沖區大小
 48     private void initPipe(int pipeSize) {
 49         if (pipeSize <= 0) {
 50             throw new IllegalArgumentException("Pipe size <= 0");
 51         }
 52         buffer = new char[pipeSize];
 53     }
 54 
 55     // 將“PipedReader”和“PipedWriter”綁定。
 56     // 實際上,這里調用的是PipedWriter的connect()函數
 57     public void connect(PipedWriter src) throws IOException {
 58         src.connect(this);
 59     }
 60 
 61     // 接收int類型的數據b。
 62     // 它只會在PipedWriter的write(int b)中會被調用
 63     synchronized void receive(int c) throws IOException {
 64         // 檢查管道狀態
 65         if (!connected) {
 66             throw new IOException("Pipe not connected");
 67         } else if (closedByWriter || closedByReader) {
 68             throw new IOException("Pipe closed");
 69         } else if (readSide != null && !readSide.isAlive()) {
 70             throw new IOException("Read end dead");
 71         }
 72 
 73         // 獲取“寫入管道”的線程
 74         writeSide = Thread.currentThread();
 75         // 如果“管道中被讀取的數據,等於寫入管道的數據”時,
 76         // 則每隔1000ms檢查“管道狀態”,並喚醒管道操作:若有“讀取管道數據線程被阻塞”,則喚醒該線程。
 77         while (in == out) {
 78             if ((readSide != null) && !readSide.isAlive()) {
 79                 throw new IOException("Pipe broken");
 80             }
 81             /* full: kick any waiting readers */
 82             notifyAll();
 83             try {
 84                 wait(1000);
 85             } catch (InterruptedException ex) {
 86                 throw new java.io.InterruptedIOException();
 87             }
 88         }
 89         if (in < 0) {
 90             in = 0;
 91             out = 0;
 92         }
 93         buffer[in++] = (char) c;
 94         if (in >= buffer.length) {
 95             in = 0;
 96         }
 97     }
 98 
 99     // 接收字符數組b。
100     synchronized void receive(char c[], int off, int len)  throws IOException {
101         while (--len >= 0) {
102             receive(c[off++]);
103         }
104     }
105 
106     // 當PipedWriter被關閉時,被調用
107     synchronized void receivedLast() {
108         closedByWriter = true;
109         notifyAll();
110     }
111 
112     // 從管道(的緩沖)中讀取一個字符,並將其轉換成int類型
113     public synchronized int read()  throws IOException {
114         if (!connected) {
115             throw new IOException("Pipe not connected");
116         } else if (closedByReader) {
117             throw new IOException("Pipe closed");
118         } else if (writeSide != null && !writeSide.isAlive()
119                    && !closedByWriter && (in < 0)) {
120             throw new IOException("Write end dead");
121         }
122 
123         readSide = Thread.currentThread();
124         int trials = 2;
125         while (in < 0) {
126             if (closedByWriter) {
127                 /* closed by writer, return EOF */
128                 return -1;
129             }
130             if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {
131                 throw new IOException("Pipe broken");
132             }
133             /* might be a writer waiting */
134             notifyAll();
135             try {
136                 wait(1000);
137             } catch (InterruptedException ex) {
138                 throw new java.io.InterruptedIOException();
139             }
140         }
141         int ret = buffer[out++];
142         if (out >= buffer.length) {
143             out = 0;
144         }
145         if (in == out) {
146             /* now empty */
147             in = -1;
148         }
149         return ret;
150     }
151 
152     // 從管道(的緩沖)中讀取數據,並將其存入到數組b中
153     public synchronized int read(char cbuf[], int off, int len)  throws IOException {
154         if (!connected) {
155             throw new IOException("Pipe not connected");
156         } else if (closedByReader) {
157             throw new IOException("Pipe closed");
158         } else if (writeSide != null && !writeSide.isAlive()
159                    && !closedByWriter && (in < 0)) {
160             throw new IOException("Write end dead");
161         }
162 
163         if ((off < 0) || (off > cbuf.length) || (len < 0) ||
164             ((off + len) > cbuf.length) || ((off + len) < 0)) {
165             throw new IndexOutOfBoundsException();
166         } else if (len == 0) {
167             return 0;
168         }
169 
170         /* possibly wait on the first character */
171         int c = read();
172         if (c < 0) {
173             return -1;
174         }
175         cbuf[off] =  (char)c;
176         int rlen = 1;
177         while ((in >= 0) && (--len > 0)) {
178             cbuf[off + rlen] = buffer[out++];
179             rlen++;
180             if (out >= buffer.length) {
181                 out = 0;
182             }
183             if (in == out) {
184                 /* now empty */
185                 in = -1;
186             }
187         }
188         return rlen;
189     }
190 
191     // 是否能從管道中讀取下一個數據
192     public synchronized boolean ready() throws IOException {
193         if (!connected) {
194             throw new IOException("Pipe not connected");
195         } else if (closedByReader) {
196             throw new IOException("Pipe closed");
197         } else if (writeSide != null && !writeSide.isAlive()
198                    && !closedByWriter && (in < 0)) {
199             throw new IOException("Write end dead");
200         }
201         if (in < 0) {
202             return false;
203         } else {
204             return true;
205         }
206     }
207 
208     // 關閉PipedReader
209     public void close()  throws IOException {
210         in = -1;
211         closedByReader = true;
212     }
213 }
View Code

 

示例

下面,我們看看多線程中通過PipedWriter和PipedReader通信的例子。例子中包括3個類:Receiver.java, Sender.java 和 PipeTest.java

Receiver.java的代碼如下:

 1 import java.io.IOException;   
 2    
 3 import java.io.PipedReader;   
 4    
 5 @SuppressWarnings("all")   
 6 /**  
 7  * 接收者線程  
 8  */   
 9 public class Receiver extends Thread {   
10        
11     // 管道輸入流對象。
12     // 它和“管道輸出流(PipedWriter)”對象綁定,
13     // 從而可以接收“管道輸出流”的數據,再讓用戶讀取。
14     private PipedReader in = new PipedReader();   
15    
16     // 獲得“管道輸入流對象”
17     public PipedReader getReader(){   
18         return in;   
19     }   
20        
21     @Override
22     public void run(){   
23         readMessageOnce() ;
24         //readMessageContinued() ;
25     }
26 
27     // 從“管道輸入流”中讀取1次數據
28     public void readMessageOnce(){   
29         // 雖然buf的大小是2048個字符,但最多只會從“管道輸入流”中讀取1024個字符。
30         // 因為,“管道輸入流”的緩沖區大小默認只有1024個字符。
31         char[] buf = new char[2048];   
32         try {   
33             int len = in.read(buf);   
34             System.out.println(new String(buf,0,len));   
35             in.close();   
36         } catch (IOException e) {   
37             e.printStackTrace();   
38         }   
39     }
40 
41     // 從“管道輸入流”讀取>1024個字符時,就停止讀取
42     public void readMessageContinued(){
43         int total=0;
44         while(true) {
45             char[] buf = new char[1024];
46             try {
47                 int len = in.read(buf);
48                 total += len;
49                 System.out.println(new String(buf,0,len));
50                 // 若讀取的字符總數>1024,則退出循環。
51                 if (total > 1024)
52                     break;
53             } catch (IOException e) {
54                 e.printStackTrace();
55             }
56         }
57 
58         try {
59             in.close(); 
60         } catch (IOException e) {   
61             e.printStackTrace();   
62         }   
63     }   
64 }
View Code

Sender.java的代碼如下:

 1 import java.io.IOException;   
 2    
 3 import java.io.PipedWriter;   
 4 @SuppressWarnings("all")
 5 /**  
 6  * 發送者線程  
 7  */   
 8 public class Sender extends Thread {   
 9        
10     // 管道輸出流對象。
11     // 它和“管道輸入流(PipedReader)”對象綁定,
12     // 從而可以將數據發送給“管道輸入流”的數據,然后用戶可以從“管道輸入流”讀取數據。
13     private PipedWriter out = new PipedWriter();
14 
15     // 獲得“管道輸出流”對象
16     public PipedWriter getWriter(){
17         return out;
18     }   
19 
20     @Override
21     public void run(){   
22         writeShortMessage();
23         //writeLongMessage();
24     }   
25 
26     // 向“管道輸出流”中寫入一則較簡短的消息:"this is a short message" 
27     private void writeShortMessage() {
28         String strInfo = "this is a short message" ;
29         try {
30             out.write(strInfo.toCharArray());
31             out.close();   
32         } catch (IOException e) {   
33             e.printStackTrace();   
34         }   
35     }
36     // 向“管道輸出流”中寫入一則較長的消息
37     private void writeLongMessage() {
38         StringBuilder sb = new StringBuilder();
39         // 通過for循環寫入1020個字符
40         for (int i=0; i<102; i++)
41             sb.append("0123456789");
42         // 再寫入26個字符。
43         sb.append("abcdefghijklmnopqrstuvwxyz");
44         // str的總長度是1020+26=1046個字符
45         String str = sb.toString();
46         try {
47             // 將1046個字符寫入到“管道輸出流”中
48             out.write(str);
49             out.close();
50         } catch (IOException e) {
51             e.printStackTrace();
52         }
53     }
54 }
View Code

PipeTest.java的代碼如下:

 1 import java.io.PipedReader;
 2 import java.io.PipedWriter;
 3 import java.io.IOException;
 4 
 5 @SuppressWarnings("all")   
 6 /**  
 7  * 管道輸入流和管道輸出流的交互程序
 8  */   
 9 public class PipeTest {   
10    
11     public static void main(String[] args) {   
12         Sender t1 = new Sender();   
13            
14         Receiver t2 = new Receiver();   
15            
16         PipedWriter out = t1.getWriter();   
17  
18         PipedReader in = t2.getReader();   
19 
20         try {   
21             //管道連接。下面2句話的本質是一樣。
22             //out.connect(in);   
23             in.connect(out);   
24                
25             /**  
26              * Thread類的START方法:  
27              * 使該線程開始執行;Java 虛擬機調用該線程的 run 方法。   
28              * 結果是兩個線程並發地運行;當前線程(從調用返回給 start 方法)和另一個線程(執行其 run 方法)。   
29              * 多次啟動一個線程是非法的。特別是當線程已經結束執行后,不能再重新啟動。   
30              */
31             t1.start();
32             t2.start();
33         } catch (IOException e) {
34             e.printStackTrace();
35         }
36     }
37 }
View Code

 

運行結果

this is a short message
結果說明
(01) in.connect(out);

        它的作用是將“管道輸入流”和“管道輸出流”關聯起來。查看PipedWriter.java和PipedReader.java中connect()的源碼;我們知道 out.connect(in); 等價於 in.connect(out);
(02)
t1.start(); // 啟動“Sender”線程
t2.start(); // 啟動“Receiver”線程
先查看Sender.java的源碼,線程啟動后執行run()函數;在Sender.java的run()中,調用writeShortMessage();
writeShortMessage();的作用就是向“管道輸出流”中寫入數據"this is a short message" ;這條數據會被“管道輸入流”接收到。下面看看這是如何實現的。
先看write(char char的源碼。PipedWriter.java繼承於Writer.java;Writer.java中write(char c[])的源碼如下:

public void write(char cbuf[]) throws IOException {
    write(cbuf, 0, cbuf.length);
}

實際上write(char c[])是調用的PipedWriter.java中的write(char c[], int off, int len)函數。查看write(char c[], int off, int len)的源碼,我們發現:它會調用 sink.receive(cbuf, off, len); 進一步查看receive(char c[], int off, int len)的定義,我們知道sink.receive(cbuf, off, len)的作用就是:將“管道輸出流”中的數據保存到“管道輸入流”的緩沖中。而“管道輸入流”的緩沖區buffer的默認大小是1024個字符。

至此,我們知道:t1.start()啟動Sender線程,而Sender線程會將數據"this is a short message"寫入到“管道輸出流”;而“管道輸出流”又會將該數據傳輸給“管道輸入流”,即而保存在“管道輸入流”的緩沖中。


接下來,我們看看“用戶如何從‘管道輸入流’的緩沖中讀取數據”。這實際上就是Receiver線程的動作。
t2.start() 會啟動Receiver線程,從而執行Receiver.java的run()函數。查看Receiver.java的源碼,我們知道run()調用了readMessageOnce()。
而readMessageOnce()就是調用in.read(buf)從“管道輸入流in”中讀取數據,並保存到buf中。
通過上面的分析,我們已經知道“管道輸入流in”的緩沖中的數據是"this is a short message";因此,buf的數據就是"this is a short message"。


為了加深對管道的理解。我們接着進行下面兩個小試驗。
試驗一:修改Sender.java

public void run(){   
    writeShortMessage();
    //writeLongMessage();
}

修改為

public void run(){   
    //writeShortMessage();
    writeLongMessage();
}

運行程序。運行結果如下:

從中,我們看出,程序運行出錯!拋出異常 java.io.IOException: Pipe closed

為什么會這樣呢?
我分析一下程序流程。
(01) 在PipeTest中,通過in.connect(out)將輸入和輸出管道連接起來;然后,啟動兩個線程。t1.start()啟動了線程Sender,t2.start()啟動了線程Receiver。
(02) Sender線程啟動后,通過writeLongMessage()寫入數據到“輸出管道”,out.write(str.toCharArray())共寫入了1046個字符。而根據PipedWriter的源碼,PipedWriter的write()函數會調用PipedReader的receive()函數。而觀察PipedReader的receive()函數,我們知道,PipedReader會將接受的數據存儲緩沖區。仔細觀察receive()函數,有如下代碼:

while (in == out) {
    if ((readSide != null) && !readSide.isAlive()) {
        throw new IOException("Pipe broken");
    }
    /* full: kick any waiting readers */
    notifyAll();
    try {
        wait(1000);
    } catch (InterruptedException ex) {
        throw new java.io.InterruptedIOException();
    }
}

而in和out的初始值分別是in=-1, out=0;結合上面的while(in==out)。我們知道,它的含義就是,每往管道中寫入一個字符,就達到了in==out這個條件。然后,就調用notifyAll(),喚醒“讀取管道的線程”。
也就是,每往管道中寫入一個字符,都會阻塞式的等待其它線程讀取。
然而,PipedReader的緩沖區的默認大小是1024!但是,此時要寫入的數據卻有1046!所以,一次性最多只能寫入1024個字符。
(03) Receiver線程啟動后,會調用readMessageOnce()讀取管道輸入流。讀取1024個字符會,會調用close()關閉,管道。

由(02)和(03)的分析可知,Sender要往管道寫入1046個字符。其中,前1024個字符(緩沖區容量是1024)能正常寫入,並且每寫入一個就讀取一個。當寫入1025個字符時,依然是依次的調用PipedWriter.java中的write();然后,write()中調用PipedReader.java中的receive();在PipedReader.java中,最終又會調用到receive(int c)函數。 而此時,管道輸入流已經被關閉,也就是closedByReader為true,所以拋出throw new IOException("Pipe closed")。

我們對“試驗一”繼續進行修改,解決該問題。


試驗二: 在“試驗一”的基礎上繼續修改Receiver.java

public void run(){   
    readMessageOnce() ;
    //readMessageContinued() ;
}

修改為

public void run(){   
    //readMessageOnce() ;
    readMessageContinued() ;
}

此時,程序能正常運行。運行結果為:
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

012345678901234567890123456789abcd

efghijklmnopqrstuvwxyz

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM