国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java線程通信---pipe管道

2019-11-14 09:19:48
字體:
來源:轉載
供稿:網友

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.survivalescaperooms.com/songxingzhu/archive/2012/09/17/2688969.html


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 行唐县| 沅江市| 苏州市| 庆城县| 石渠县| 雷州市| 乌兰县| 曲阜市| 西吉县| 林周县| 察雅县| 廉江市| 丹江口市| 蓬莱市| 宁武县| 通海县| 上蔡县| 博爱县| 乌恰县| 广东省| 五家渠市| 仙桃市| 绥德县| 容城县| 洛宁县| 汕尾市| 武隆县| 陆河县| 龙泉市| 吉安县| 固安县| 兴和县| 灌南县| 尼勒克县| 三穗县| 松江区| 高雄市| 庄浪县| 建水县| 建水县| 仙居县|