PipedInputStream類與PipedOutputStream類用於在應用程序中創建管道通信.一個PipedInputStream實例對
象必須和一個PipedOutputStream實例對象進行連接而產生一個通信管道.PipedOutputStream可以向管道中寫入數
據,PipedIntputStream可以讀取PipedOutputStream向管道中寫入的數據.這兩個類主要用來完成線程之間的通信.一個線程
的PipedInputStream對象能夠從另外一個線程的PipedOutputStream對象中讀取數據.
PipedInputStream與PipedOutputStream類的編程實例(兩個線程間進行通信的實例程序)
發送者
import java.io.IOException;
import java.io.PipedOutputStream;
import java.util.Scanner;
public class Sender extends Thread {
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOut(){
return out;
}
public void run(){
System.out.println("請輸入您要發送的內容:");
Scanner sc = new Scanner(System.in);
String comtent = sc.next();
//String strInfo = new String("Hello,rec");
try {
//out.write(strInfo.getBytes());
out.write(comtent.getBytes());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.out.println(e);
}
}
}
接收者
import java.io.IOException;
import java.io.PipedInputStream;
public class Receiver extends Thread{
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getIn(){
return in;
}
public void run(){
byte [] buf = new byte[1024];
try {
int len = in.read(buf);
System.out.println("the following message comes form sender:/n"
+new String(buf,0,len));
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.out.println(e);
}
}
}
測試程序
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sender send = new Sender();
Receiver receiv = new Receiver();
PipedOutputStream out = send.getOut();
PipedInputStream in = receiv.getIn();
try {
out.connect(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
send.start();
receiv.start();
}
}