掌握線程通訊流(管道流)的使用
管道流的主要作用是可以進行兩個線程間的通訊,分為管道輸入流(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。
總結:
開發中很少直接開發多線程程序,本道程序,只是讓讀者加深讀寫的操作過程,了解,線程間如何通訊。