本章,我們對java 管道進行學習。
轉載請注明出處:http://www.cnblogs.com/skywang12345/p/io_04.html
java 管道介紹
在java中,PipedOutputStream和PipedInputStream分別是管道輸出流和管道輸入流。
它們的作用是讓多線程可以通過管道進行線程間的通訊。在使用管道通信時,必須將PipedOutputStream和PipedInputStream配套使用。
使用管道通信時,大致的流程是:我們在線程A中向PipedOutputStream中寫入數據,這些數據會自動的發送到與PipedOutputStream對應的PipedInputStream中,進而存儲在PipedInputStream的緩沖中;此時,線程B通過讀取PipedInputStream中的數據。就可以實現,線程A和線程B的通信。
PipedOutputStream和PipedInputStream源碼分析
下面介紹PipedOutputStream和PipedInputStream的源碼。在閱讀它們的源碼之前,建議先看看源碼后面的示例。待理解管道的作用和用法之后,再看源碼,可能更容易理解。
此外,由於在“java io系列03之 ByteArrayOutputStream的簡介,源碼分析和示例(包括OutputStream)”中已經對PipedOutputStream的父類OutputStream進行了介紹,這里就不再介紹OutputStream。
在“java io系列02之 ByteArrayInputStream的簡介,源碼分析和示例(包括InputStream)”中已經對PipedInputStream的父類InputStream進行了介紹,這里也不再介紹InputStream。
1. PipedOutputStream 源碼分析(基於jdk1.7.40)

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

1 package java.io; 2 3 public class PipedInputStream extends InputStream { 4 // “管道輸出流”是否關閉的標記 5 boolean closedByWriter = false; 6 // “管道輸入流”是否關閉的標記 7 volatile boolean closedByReader = false; 8 // “管道輸入流”與“管道輸出流”是否連接的標記 9 // 它在PipedOutputStream的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 protected static final int PIPE_SIZE = DEFAULT_PIPE_SIZE; 19 20 // 緩沖區 21 protected byte buffer[]; 22 23 //下一個寫入字節的位置。in==out代表滿,說明“寫入的數據”全部被讀取了。 24 protected int in = -1; 25 //下一個讀取字節的位置。in==out代表滿,說明“寫入的數據”全部被讀取了。 26 protected int out = 0; 27 28 // 構造函數:指定與“管道輸入流”關聯的“管道輸出流” 29 public PipedInputStream(PipedOutputStream src) throws IOException { 30 this(src, DEFAULT_PIPE_SIZE); 31 } 32 33 // 構造函數:指定與“管道輸入流”關聯的“管道輸出流”,以及“緩沖區大小” 34 public PipedInputStream(PipedOutputStream src, int pipeSize) 35 throws IOException { 36 initPipe(pipeSize); 37 connect(src); 38 } 39 40 // 構造函數:默認緩沖區大小是1024字節 41 public PipedInputStream() { 42 initPipe(DEFAULT_PIPE_SIZE); 43 } 44 45 // 構造函數:指定緩沖區大小是pipeSize 46 public PipedInputStream(int pipeSize) { 47 initPipe(pipeSize); 48 } 49 50 // 初始化“管道”:新建緩沖區大小 51 private void initPipe(int pipeSize) { 52 if (pipeSize <= 0) { 53 throw new IllegalArgumentException("Pipe Size <= 0"); 54 } 55 buffer = new byte[pipeSize]; 56 } 57 58 // 將“管道輸入流”和“管道輸出流”綁定。 59 // 實際上,這里調用的是PipedOutputStream的connect()函數 60 public void connect(PipedOutputStream src) throws IOException { 61 src.connect(this); 62 } 63 64 // 接收int類型的數據b。 65 // 它只會在PipedOutputStream的write(int b)中會被調用 66 protected synchronized void receive(int b) throws IOException { 67 // 檢查管道狀態 68 checkStateForReceive(); 69 // 獲取“寫入管道”的線程 70 writeSide = Thread.currentThread(); 71 // 若“寫入管道”的數據正好全部被讀取完,則等待。 72 if (in == out) 73 awaitSpace(); 74 if (in < 0) { 75 in = 0; 76 out = 0; 77 } 78 // 將b保存到緩沖區 79 buffer[in++] = (byte)(b & 0xFF); 80 if (in >= buffer.length) { 81 in = 0; 82 } 83 } 84 85 // 接收字節數組b。 86 synchronized void receive(byte b[], int off, int len) throws IOException { 87 // 檢查管道狀態 88 checkStateForReceive(); 89 // 獲取“寫入管道”的線程 90 writeSide = Thread.currentThread(); 91 int bytesToTransfer = len; 92 while (bytesToTransfer > 0) { 93 // 若“寫入管道”的數據正好全部被讀取完,則等待。 94 if (in == out) 95 awaitSpace(); 96 int nextTransferAmount = 0; 97 // 如果“管道中被讀取的數據,少於寫入管道的數據”; 98 // 則設置nextTransferAmount=“buffer.length - in” 99 if (out < in) { 100 nextTransferAmount = buffer.length - in; 101 } else if (in < out) { // 如果“管道中被讀取的數據,大於/等於寫入管道的數據”,則執行后面的操作 102 // 若in==-1(即管道的寫入數據等於被讀取數據),此時nextTransferAmount = buffer.length - in; 103 // 否則,nextTransferAmount = out - in; 104 if (in == -1) { 105 in = out = 0; 106 nextTransferAmount = buffer.length - in; 107 } else { 108 nextTransferAmount = out - in; 109 } 110 } 111 if (nextTransferAmount > bytesToTransfer) 112 nextTransferAmount = bytesToTransfer; 113 // assert斷言的作用是,若nextTransferAmount <= 0,則終止程序。 114 assert(nextTransferAmount > 0); 115 // 將數據寫入到緩沖中 116 System.arraycopy(b, off, buffer, in, nextTransferAmount); 117 bytesToTransfer -= nextTransferAmount; 118 off += nextTransferAmount; 119 in += nextTransferAmount; 120 if (in >= buffer.length) { 121 in = 0; 122 } 123 } 124 } 125 126 // 檢查管道狀態 127 private void checkStateForReceive() throws IOException { 128 if (!connected) { 129 throw new IOException("Pipe not connected"); 130 } else if (closedByWriter || closedByReader) { 131 throw new IOException("Pipe closed"); 132 } else if (readSide != null && !readSide.isAlive()) { 133 throw new IOException("Read end dead"); 134 } 135 } 136 137 // 等待。 138 // 若“寫入管道”的數據正好全部被讀取完(例如,管道緩沖滿),則執行awaitSpace()操作; 139 // 它的目的是讓“讀取管道的線程”管道產生讀取數據請求,從而才能繼續的向“管道”中寫入數據。 140 private void awaitSpace() throws IOException { 141 142 // 如果“管道中被讀取的數據,等於寫入管道的數據”時, 143 // 則每隔1000ms檢查“管道狀態”,並喚醒管道操作:若有“讀取管道數據線程被阻塞”,則喚醒該線程。 144 while (in == out) { 145 checkStateForReceive(); 146 147 /* full: kick any waiting readers */ 148 notifyAll(); 149 try { 150 wait(1000); 151 } catch (InterruptedException ex) { 152 throw new java.io.InterruptedIOException(); 153 } 154 } 155 } 156 157 // 當PipedOutputStream被關閉時,被調用 158 synchronized void receivedLast() { 159 closedByWriter = true; 160 notifyAll(); 161 } 162 163 // 從管道(的緩沖)中讀取一個字節,並將其轉換成int類型 164 public synchronized int read() throws IOException { 165 if (!connected) { 166 throw new IOException("Pipe not connected"); 167 } else if (closedByReader) { 168 throw new IOException("Pipe closed"); 169 } else if (writeSide != null && !writeSide.isAlive() 170 && !closedByWriter && (in < 0)) { 171 throw new IOException("Write end dead"); 172 } 173 174 readSide = Thread.currentThread(); 175 int trials = 2; 176 while (in < 0) { 177 if (closedByWriter) { 178 /* closed by writer, return EOF */ 179 return -1; 180 } 181 if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) { 182 throw new IOException("Pipe broken"); 183 } 184 /* might be a writer waiting */ 185 notifyAll(); 186 try { 187 wait(1000); 188 } catch (InterruptedException ex) { 189 throw new java.io.InterruptedIOException(); 190 } 191 } 192 int ret = buffer[out++] & 0xFF; 193 if (out >= buffer.length) { 194 out = 0; 195 } 196 if (in == out) { 197 /* now empty */ 198 in = -1; 199 } 200 201 return ret; 202 } 203 204 // 從管道(的緩沖)中讀取數據,並將其存入到數組b中 205 public synchronized int read(byte b[], int off, int len) throws IOException { 206 if (b == null) { 207 throw new NullPointerException(); 208 } else if (off < 0 || len < 0 || len > b.length - off) { 209 throw new IndexOutOfBoundsException(); 210 } else if (len == 0) { 211 return 0; 212 } 213 214 /* possibly wait on the first character */ 215 int c = read(); 216 if (c < 0) { 217 return -1; 218 } 219 b[off] = (byte) c; 220 int rlen = 1; 221 while ((in >= 0) && (len > 1)) { 222 223 int available; 224 225 if (in > out) { 226 available = Math.min((buffer.length - out), (in - out)); 227 } else { 228 available = buffer.length - out; 229 } 230 231 // A byte is read beforehand outside the loop 232 if (available > (len - 1)) { 233 available = len - 1; 234 } 235 System.arraycopy(buffer, out, b, off + rlen, available); 236 out += available; 237 rlen += available; 238 len -= available; 239 240 if (out >= buffer.length) { 241 out = 0; 242 } 243 if (in == out) { 244 /* now empty */ 245 in = -1; 246 } 247 } 248 return rlen; 249 } 250 251 // 返回不受阻塞地從此輸入流中讀取的字節數。 252 public synchronized int available() throws IOException { 253 if(in < 0) 254 return 0; 255 else if(in == out) 256 return buffer.length; 257 else if (in > out) 258 return in - out; 259 else 260 return in + buffer.length - out; 261 } 262 263 // 關閉管道輸入流 264 public void close() throws IOException { 265 closedByReader = true; 266 synchronized (this) { 267 in = -1; 268 } 269 } 270 }
管道通信示例
下面,我們看看多線程中通過管道通信的例子。例子中包括3個類:Receiver.java, PipedStreamTest.java 和 Sender.java。
Receiver.java的代碼如下:

1 import java.io.IOException; 2 3 import java.io.PipedInputStream; 4 5 @SuppressWarnings("all") 6 /** 7 * 接收者線程 8 */ 9 public class Receiver extends Thread { 10 11 // 管道輸入流對象。 12 // 它和“管道輸出流(PipedOutputStream)”對象綁定, 13 // 從而可以接收“管道輸出流”的數據,再讓用戶讀取。 14 private PipedInputStream in = new PipedInputStream(); 15 16 // 獲得“管道輸入流”對象 17 public PipedInputStream getInputStream(){ 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 byte[] buf = new byte[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 // 從“管道輸入流”讀取>1024個字節時,就停止讀取 41 public void readMessageContinued() { 42 int total=0; 43 while(true) { 44 byte[] buf = new byte[1024]; 45 try { 46 int len = in.read(buf); 47 total += len; 48 System.out.println(new String(buf,0,len)); 49 // 若讀取的字節總數>1024,則退出循環。 50 if (total > 1024) 51 break; 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 } 56 57 try { 58 in.close(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 }
Sender.java的代碼如下:

1 import java.io.IOException; 2 3 import java.io.PipedOutputStream; 4 @SuppressWarnings("all") 5 /** 6 * 發送者線程 7 */ 8 public class Sender extends Thread { 9 10 // 管道輸出流對象。 11 // 它和“管道輸入流(PipedInputStream)”對象綁定, 12 // 從而可以將數據發送給“管道輸入流”的數據,然后用戶可以從“管道輸入流”讀取數據。 13 private PipedOutputStream out = new PipedOutputStream(); 14 15 // 獲得“管道輸出流”對象 16 public PipedOutputStream getOutputStream(){ 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.getBytes()); 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.getBytes()); 49 out.close(); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 }
PipedStreamTest.java的代碼如下:

1 import java.io.PipedInputStream; 2 import java.io.PipedOutputStream; 3 import java.io.IOException; 4 5 @SuppressWarnings("all") 6 /** 7 * 管道輸入流和管道輸出流的交互程序 8 */ 9 public class PipedStreamTest { 10 11 public static void main(String[] args) { 12 Sender t1 = new Sender(); 13 14 Receiver t2 = new Receiver(); 15 16 PipedOutputStream out = t1.getOutputStream(); 17 18 PipedInputStream in = t2.getInputStream(); 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 }
運行結果:
this is a short message
說明:
(01)
in.connect(out);
將“管道輸入流”和“管道輸出流”關聯起來。查看PipedOutputStream.java和PipedInputStream.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(byte b[])的源碼,在OutputStream.java中定義。PipedOutputStream.java繼承於OutputStream.java;OutputStream.java中write(byte b[])的源碼如下:
public void write(byte b[]) throws IOException { write(b, 0, b.length); }
實際上write(byte b[])是調用的PipedOutputStream.java中的write(byte b[], int off, int len)函數。查看write(byte b[], int off, int len)的源碼,我們發現:它會調用 sink.receive(b, off, len); 進一步查看receive(byte b[], int off, int len)的定義,我們知道sink.receive(b, 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(); }
運行程序。運行結果為:
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd
這些數據是通過writeLongMessage()寫入到“管道輸出流”,然后傳送給“管道輸入流”,進而存儲在“管道輸入流”的緩沖中;再被用戶從緩沖讀取出來的數據。
然后,觀察writeLongMessage()的源碼。我們可以發現,str的長度是1046個字節,然后運行結果只有1024個字節!為什么會這樣呢?
道理很簡單:管道輸入流的緩沖區默認大小是1024個字節。所以,最多只能寫入1024個字節。
觀察PipedInputStream.java的源碼,我們能了解的更透徹。
private static final int DEFAULT_PIPE_SIZE = 1024; public PipedInputStream() { initPipe(DEFAULT_PIPE_SIZE); }
默認構造函數調用initPipe(DEFAULT_PIPE_SIZE),它的源碼如下:
private void initPipe(int pipeSize) { if (pipeSize <= 0) { throw new IllegalArgumentException("Pipe Size <= 0"); } buffer = new byte[pipeSize]; }
從中,我們可以知道緩沖區buffer的默認大小就是1024個字節。
試驗二: 在“試驗一”的基礎上繼續修改Receiver.java
將
public void run(){ readMessageOnce() ; //readMessageContinued() ; }
修改為
public void run(){ //readMessageOnce() ; readMessageContinued() ; }
運行程序。運行結果為:
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd
efghijklmnopqrstuvwxyz
這個結果才是writeLongMessage()寫入到“輸入緩沖區”的完整數據。
更多內容
3. java io系列02之 ByteArrayInputStream的簡介,源碼分析和示例(包括InputStream)
4. java io系列03之 ByteArrayOutputStream的簡介,源碼分析和示例(包括OutputStream)