在之前學習的幾種IO流中不難發現,它們在面對線程間通信問題的時候顯然無法實作IO操作,這時需要用到本節介紹的管道流來進行處理。
【本節目标】
通過閱讀本節内容,你将了解到幾種管道流實作類的繼承關系及其相關方法的功能,并結合執行個體代碼實作線程間的資料通信工作。
管道流
管道流主要功能是實作兩個線程之間的IO處理操作。

對于管道流也分為兩類:
位元組管道流:PipedOutputStream、PipedInputStream
|- 連接配接處理:public void connect(PipedInputStream snk) throws IOException;
字元管道流:PipedWriter、PipedReader
|- 連接配接處理:public void connect(PipedReader snk) throws IOException;
PipedOutputStream
PipedInputStream
PipedWriter
PipedReader
範例:實作管道操作
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
class JavaAPIDemo {
public static void main(String[] args) throws Exception {
SendThread send=new SendThread();
ReceiveThread receive=new ReceiveThread();
send.getOutput().connect(receive.getInput());//進行管道連接配接
new Thread(send,"消息發送線程").start();
new Thread(receive,"消息接收線程").start();
}
}
class SendThread implements Runnable{
private PipedOutputStream output; //管道輸出流
public SendThread() {
this.output = new PipedOutputStream(); //執行個體化管道輸出流
}
@Override
public void run() {
try { //利用管道實作資料的發送處理
this.output.write(("【資訊發送 - "+Thread.currentThread().getName()+"】www.mldn.cn\n").getBytes());
}catch (IOException e){
e.printStackTrace();
}
try {
this.output.close();
}catch (IOException e){
e.printStackTrace();
}
}
public PipedOutputStream getOutput(){
return output;
}
}
class ReceiveThread implements Runnable{
private PipedInputStream input;
public ReceiveThread() {
this.input = new PipedInputStream();
}
@Override
public void run() {
byte[] data = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();//所有的資料儲存到記憶體輸出流
try {
while ((len = input.read(data)) != -1) {
bos.write(data, 0, len); //所有的資料儲存在記憶體流裡面
}
System.out.println("{" +Thread.currentThread().getName()+"接收消息}\n"+ new String(bos.toByteArray()));
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
this.input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public PipedInputStream getInput() {
return input;
}
}
執行結果:
{消息接收線程接收消息}【資訊發送 - 消息發送線程】www.mldn.cn
管道就類似于在醫院打點滴的效果,一個負責發送,一個負責接收,中間靠一個管道連接配接。
想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。
本内容視訊來源于
阿裡雲大學 下一篇:“一目十行”的RandomAccessFile類 | 帶你學《Java語言進階特性》之六十三 更多Java面向對象程式設計文章檢視此處