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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

java線程通信---pipe管道

2019-11-14 08:50:14
字體:
供稿:網(wǎng)友

java線程之間的通信方式也比較多,這里總結(jié)一下自己理解的pipe管道通信。

一、建立管道輸入端和輸出端的連接 首先為了創(chuàng)建一個(gè)管道流,我們必須首先創(chuàng)建一個(gè)PipedOutputStream對(duì)象,然后創(chuàng)建一個(gè)PipedInputStream對(duì)象。如下: PipedOutputStream out = null; PipedInputStream in = null; 對(duì)象建立好以后使用connect()方法將二者建立連接 out.connect(in); 該方法在PipedOutputStream 、PipedInputStream當(dāng)中都有,隨便調(diào)用那個(gè)來建立連接都可以,但注意智能建立一次連接,重復(fù)建立會(huì)拋異常。 不使用connect()方法也是可以建立連接的,方法如下: out = new PipedOutputStream(in ); 一旦建立了管道,就可以像操作文件一樣對(duì)管道進(jìn)行數(shù)據(jù)讀寫。

二、開始通信 首先有一點(diǎn)特別注意,不能在同一個(gè)線程當(dāng)中既寫入又讀取,這樣會(huì)造成死鎖,因?yàn)楣艿罆?huì)有阻塞的時(shí)候(當(dāng)管道當(dāng)中沒有數(shù)據(jù),進(jìn)行讀操作時(shí),讀操作的線程會(huì)阻塞,直到有線程來寫數(shù)據(jù);當(dāng)管道當(dāng)中滿數(shù)據(jù),進(jìn)行寫操作時(shí),寫操作的線程阻塞,直到有線程來讀數(shù)據(jù)),有時(shí)需要寫和讀的兩端同時(shí)都在工作,只有一個(gè)線程去完成讀和寫,顯然無法保證能夠同時(shí)讀寫,所以讀寫最好放在單獨(dú)的線程去完成。 建立的管道是一個(gè)包含1024字節(jié)大小的循環(huán)緩沖數(shù)組,從管道當(dāng)中讀取的數(shù)據(jù),會(huì)被清除出管道,即是讀取以后就相當(dāng)于把該數(shù)據(jù)從管道當(dāng)中拿走了,所以是循環(huán)緩沖數(shù)組。 下面演示代碼:

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()); } }}

運(yùn)行結(jié)果如下:

這里寫圖片描述

參考文章: http://blog.csdn.net/zlp1992/article/details/50298195#comments http://m.survivalescaperooms.com/songxingzhu/archive/2012/09/17/2688969.html


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 鹿泉市| 平顶山市| 岳普湖县| 女性| 民勤县| 南昌县| 东海县| 宜宾县| 临沧市| 左云县| 西乌珠穆沁旗| 天气| 江城| 松潘县| 江源县| 平阴县| 建昌县| 栾城县| 鹤庆县| 高唐县| 四平市| 襄城县| 黄浦区| 股票| 东丽区| 建瓯市| 大理市| 湄潭县| 皮山县| 万荣县| 泰兴市| 酒泉市| 二手房| 宁武县| 错那县| 南漳县| 博罗县| 乌苏市| 阳信县| 肥城市| 那坡县|