java線程之間的通信方式也比較多,這里總結一下自己理解的pipe管道通信。
一、建立管道輸入端和輸出端的連接 首先為了創建一個管道流,我們必須首先創建一個PipedOutputStream對象,然后創建一個PipedInputStream對象。如下: PipedOutputStream out = null; PipedInputStream in = null; 對象建立好以后使用connect()方法將二者建立連接 out.connect(in); 該方法在PipedOutputStream 、PipedInputStream當中都有,隨便調用那個來建立連接都可以,但注意智能建立一次連接,重復建立會拋異常。 不使用connect()方法也是可以建立連接的,方法如下: out = new PipedOutputStream(in ); 一旦建立了管道,就可以像操作文件一樣對管道進行數據讀寫。
二、開始通信 首先有一點特別注意,不能在同一個線程當中既寫入又讀取,這樣會造成死鎖,因為管道會有阻塞的時候(當管道當中沒有數據,進行讀操作時,讀操作的線程會阻塞,直到有線程來寫數據;當管道當中滿數據,進行寫操作時,寫操作的線程阻塞,直到有線程來讀數據),有時需要寫和讀的兩端同時都在工作,只有一個線程去完成讀和寫,顯然無法保證能夠同時讀寫,所以讀寫最好放在單獨的線程去完成。 建立的管道是一個包含1024字節大小的循環緩沖數組,從管道當中讀取的數據,會被清除出管道,即是讀取以后就相當于把該數據從管道當中拿走了,所以是循環緩沖數組。 下面演示代碼:
package cn.zhoucy.pipe;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class TestPiped {public static void main(String[] args) { Sender sender = new Sender(); Recive recive = new Recive(); PipedInputStream pi = recive.getPipedInputputStream(); PipedOutputStream po = sender.getPipedOutputStream(); try { pi.connect(po); } catch (IOException e) { System.out.PRintln(e.getMessage()); } new Thread(sender).start(); new Thread(recive).start();}}class Sender implements Runnable {PipedOutputStream out = null;public PipedOutputStream getPipedOutputStream() { out = new PipedOutputStream(); return out;}@Overridepublic void run() { try { out.write("Hello , Reciver!".getBytes()); } catch (IOException e) { System.out.println(e.getMessage()); } try { out.close(); } catch (IOException e) { System.out.println(e.getMessage()); }}}class Recive implements Runnable {PipedInputStream in = null;public PipedInputStream getPipedInputputStream() { in = new PipedInputStream(); return in;}@Overridepublic void run() { byte[] bys = new byte[1024]; try { in.read(bys); System.out.println("讀取到的信息:" + new String(bys).trim()); in.close(); } catch (IOException e) { System.out.println(e.getMessage()); } }}運行結果如下:
參考文章: http://blog.csdn.net/zlp1992/article/details/50298195#comments http://www.companysz.com/songxingzhu/archive/2012/09/17/2688969.html
新聞熱點
疑難解答