溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java 多線程使用PipedOutStream和PipedInputStream

發(fā)布時間:2020-08-07 18:20:15 來源:ITPUB博客 閱讀:151 作者:hgs19921112 欄目:編程語言
package test;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipeTest {
public static void main(String[] args) throws Exception {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
//鏈接
pis.connect(pos);
//寫線程
InThread it = new InThread(pos,pis);
//讀線程
OutThread ot = new OutThread(pos,pis);
it.start();
ot.start();
Thread.sleep(1000);
}
}
class InThread extends Thread{
PipedOutputStream pos = null;
PipedInputStream pis = null ;
InThread(PipedOutputStream pos,PipedInputStream pis ){
this.pos = pos;
this.pis = pis;
}
public void run() {
try {
//寫入數(shù)據(jù)
byte[] b = new String("this is a test !").getBytes();
pos.write(b);
//關(guān)閉鏈接,此處必須關(guān)閉,不然會包異常  
pos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class OutThread extends Thread{
PipedInputStream pis = null ;
PipedOutputStream pos = null;
OutThread(PipedOutputStream pos,PipedInputStream pis){
this.pis = pis;
this.pos = pos;
}
public void run() {
//讀取數(shù)據(jù)
String m = "";
byte[] b = new byte[1024];
try {
int len ;
len = pis.read(b);
m = m+ new String(b);
while(len!=-1) {
len = pis.read(b); 
m = m+ new String(b);
}
//關(guān)閉資源
pis.close();
System.out.println(m);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI