一、PipedInputStream:管道輸入流應該連接到管道輸出流;管道輸入流提供要寫入管道輸出流的所有數據字節。通常,數據由某個線程從 PipedInputStream 對象讀取,並由其他線程將其寫入到相應的 PipedOutputStream。
步驟:
輸出流一端
1、PipedOutputStream pos = null;
pos = new PipedOutputStream();
2、調用write方法寫入輸出流
3、關閉輸出流
二、PipedOutputStream:可以將管道輸出流連接到管道輸入流來創建通信管道。管道輸出流是管道的發送端。通常,數據由某個線程寫入 PipedOutputStream 對象,並由其他線程從連接的 PipedInputStream 讀取。
步驟:
輸入流一端
1、PipedInputStream pis = null;
pis = new PipedInputStream();
2、調用read方法讀取輸出流傳遞過來的信息
3、關閉輸入流
三、測試一端
1、啓動兩個線程,分別獲取發送者和接受者的輸出、輸入流
2、連接輸入流到輸出流
3、啓動線程
import java.io.*;
public class PipedDemo02 {
public static void main(String[] args) throws IOException {
SendThread st = new SendThread();
ReceiveThread rt = new ReceiveThread();
PipedOutputStream out = st.getOut();
PipedInputStream in = rt.getIn();
out.connect(in);
Thread send = new Thread(st);
Thread receive = new Thread(rt);
send.start();
receive.start();
}
}
class SendThread implements Runnable{
PipedOutputStream pos = null;
public SendThread(){
pos = new PipedOutputStream();
}
public PipedOutputStream getOut(){
return this.pos;
}
@Override
public void run() {
String str = "Hello,World";
try {
pos.write(str.getBytes());
pos.close();
} catch (IOException e) {
}
System.out.println("發送的內容:"+str);
}
}
class ReceiveThread implements Runnable{
PipedInputStream pis = null;
public ReceiveThread(){
pis = new PipedInputStream();
}
public PipedInputStream getIn(){
return this.pis;
}
@Override
public void run() {
byte b[] = new byte[1024] ;
int len = 0 ;
try{
len = pis.read(b) ;
pis.close() ;
}
catch (Exception e){
}
System.out.println("接受的內容:"+new String(b,0,len));
}
}
發送的內容:Hello,World
接受的內容:Hello,World