管道流
作用:用於線程之間的數據通信
管道流測試:一個線程寫入,一個線程讀取
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamDemo {
public static void main(String[] args) {
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream();
try {
pin.connect(pout);// 輸入流與輸出流鏈接
} catch (Exception e) {
e.printStackTrace();// 這是便於調試用的,上線的時候不需要
}
new Thread(new ReadThread(pin)).start();
new Thread(new WriteThread(pout)).start();
// 輸出結果:讀到: 一個美女。。
}
}
// 讀取數據的線程
class ReadThread implements Runnable {
private PipedInputStream pin;// 輸入管道
public ReadThread(PipedInputStream pin) {
this.pin = pin;
}
@Override
public void run() {
try {
byte[] buf = new byte[1024];
int len = pin.read(buf);// read阻塞
String s = new String(buf, 0, len);
System.out.println("讀到: " + s);
pin.close();
} catch (IOException e) {
e.printStackTrace();
}
}// run
}// ReadThread
// 寫入數據的線程
class WriteThread implements Runnable {
private PipedOutputStream pout;// 輸出管道
public WriteThread(PipedOutputStream pout) {
this.pout = pout;
}
@Override
public void run() {
try {
pout.write("一個美女。。".getBytes());// 管道輸出流
pout.close();
} catch (Exception e) {
e.printStackTrace();
}
}// run
}// WriteThread