之前我們使用io流,都是需要一個中間數組,管道流可以直接輸入流對接輸出流,一般和多線程配合使用,當讀取流中沒數據時會阻塞當前的線程,對其他線程沒有影響
定義一個類Read實現Runable接口,實現run()方法,構造方法傳遞PipedInputStream對象
讀取流裡面的數據
定義一個類Write實現Runable接口,實現run()方法,構造方法傳遞PipedOutputStream對象
寫入流裡面數據
獲取PipedInputStream對象,new出來
獲取PipedOutputStream對象,new出來
調用PipedInputStream對象的connect()方法,對接輸出流,參數:PipedOutputStream對象
開啟兩個線程執行讀寫
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 讀取數據線程
* @author taoshihan
*
*/
class ReadPipe implements Runnable{
private PipedInputStream in;
public ReadPipe(PipedInputStream in) {
this.in=in;
}
@Override
public void run() {
System.out.println("開始讀取。。。如果沒有數據會阻塞");
byte[] b=new byte[1024];
try {
int len=in.read(b);
String info=new String(b,0,len);
in.close();
System.out.println(info);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 寫入數據線程
* @author taoshihan
*
*/
class WritePipe implements Runnable{
private PipedOutputStream out;
public WritePipe(PipedOutputStream out) {
this.out=out;
}
@Override
public void run() {
System.out.println("開始寫入。。。延遲5秒");
try {
Thread.sleep(5000);
out.write("我是數據".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class PipeDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//連接管道
PipedInputStream in=new PipedInputStream();
PipedOutputStream out=new PipedOutputStream();
in.connect(out);
//開啟線程
new Thread(new ReadPipe(in)).start();
new Thread(new WritePipe(out)).start();
}
}
