標籤:類集 讀寫 receive 過程 port input back round 作用
掌握線程通訊流(管道流)的使用
管道流的主要作用是可以進行兩個線程間的通訊,分為管道輸入資料流(PipeOutputStream)和管道輸出資料流(PipeInputStream)。
如果要想進行管道輸出,則必須把輸出資料流連在輸入資料流之上,在PipeOutputStream上有如下方法用於串連管道。
void connect(PipedInputStream snk) 將此管道輸出資料流串連到接收者。
要想串連輸入和輸出,必須使用此方法、
PipeOutputStream輸出方法:
void write(byte[] b, int off, int len) 將 len 位元組從初始位移量為 off 的指定 byte 數組寫入該管道輸出資料流。
PipeInputStream輸入方法:讀取檔案的方法
將串連的PipeOutputStream對象執行個體的輸入資料流的資料,通過read方法,把內容讀取到數組中。
int read(byte[] b, int off, int len) 將最多 len 個資料位元組從此管道輸入資料流讀入 byte 數組。
執行個體代碼:
package 類集;import java.io.* ;class Send implements Runnable{ // 線程類 private PipedOutputStream pos = null ; // 管道輸出資料流 public Send(){ this.pos = new PipedOutputStream() ; // 執行個體化輸出資料流 } public void run(){ String str = "Hello World!!!" ; // 要輸出的內容 try{ this.pos.write(str.getBytes()) ; }catch(IOException e){ e.printStackTrace() ; } try{ this.pos.close() ; }catch(IOException e){ e.printStackTrace() ; } } public PipedOutputStream getPos(){ // 得到此線程的管道輸出資料流 return this.pos ; }};class Receive implements Runnable{ private PipedInputStream pis = null ; // 管道輸入資料流 public Receive(){ this.pis = new PipedInputStream() ; // 執行個體化輸入資料流 } public void run(){ byte b[] = new byte[1024] ; // 接收內容 int len = 0 ; try{ len = this.pis.read(b) ; // 讀取內容 }catch(IOException e){ e.printStackTrace() ; } try{ this.pis.close() ; // 關閉 }catch(IOException e){ e.printStackTrace() ; } System.out.println("接收的內容為:" + new String(b,0,len)) ;//注意,這裡是把讀入的數組的資料輸出,而不是PipeInputStream執行個體對象輸出, } public PipedInputStream getPis(){ return this.pis ; }};public class PipedDemo{ public static void main(String args[]){ Send s = new Send() ; Receive r = new Receive() ; try{ s.getPos().connect(r.getPis()) ; // 串連管道 }catch(IOException e){ e.printStackTrace() ; } new Thread(s).start() ; // 啟動線程 new Thread(r).start() ; // 啟動線程 }};
PipeInputStream讀取檔案後,讀取的資料都存在了PipeInputStream對象的執行個體中,且類型為byte。
總結:
開發中很少直接開發多線程程式,本道程式,只是讓讀者加深讀寫的操作過程,瞭解,線程間如何通訊。
JAVA的IO編程:管道流