管道流的主要作用是可以進行兩個線程間的通訊,分爲管道輸出流(PipedOutputStream、PipedWriter)、管道輸入流(PipedInputStream、PipedReader)
- 【PipedOutputStream】管道連接:public void connect(PipedInputStream snk) throws IOException
- 【PipedWriter】管道連接:public void connect(PipedReader snk) throws IOException
管道流(字節流)
管道流(字符流)
範例:使用字節管道流實現線程通信
package com.lxh.sixteenchapter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class JavaIODemo420 {
public static void main(String[] args) throws IOException {
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 PipedOutputStream getOutput() {
return output;
}
public void setOutput(PipedOutputStream output) {
this.output = output;
}
public SendThread() {
this.output = new PipedOutputStream();
}
@Override
public void run() {
try {
this.output.write("您好?請問需要幫助嗎?".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(output!=null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ReceiveThread implements Runnable{ //接收信息線程數據
private PipedInputStream input;
public ReceiveThread() {
this.input =new PipedInputStream();
}
public PipedInputStream getInput() {
return input;
}
public void setInput(PipedInputStream input) {
this.input = input;
}
@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(new String(bos.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}finally {
if(input!=null) {
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
執行結果
您好?請問需要幫助嗎?