【JAVA IO】_管道流筆記
本章目標:
掌握線程通訊流(管道流)的使用
管道流
管道流的主要作用是可以進行兩個線程間的通訊,分為管道輸出資料流(PipedOutputStream)、管道輸入資料流(PipedInputStream),如果要想進行管道輸出,則必須把輸出資料流連在輸入資料流之上,在PipedOutputStream類上有如下的一個方法用於串連管道。
public void connect(PipInputStream snk) throws IOException
要想實現管道流,則可以使用管道輸出資料流(PipedOutputStream)、管道輸入資料流(PipedInputStream)
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)) ; } 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() ; // 啟動線程 }};