package com.heima.code;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
//输入管道
class Read implements Runnable{
private PipedInputStream in;
Read(PipedInputStream in){
this.in = in;
}
@Override
public void run() {
try {
byte[] buf = new byte[1024];
System.out.println("读取前没有数据,阻塞了!");
int len = in.read(buf);
System.out.println("读到数据,阻塞结束!");
String s = new String(buf,0,len);
System.out.println(s);
in.close();
} catch (IOException e) {
throw new RuntimeException("管道读取流失败");
}
}
}
class Writer implements Runnable{
private PipedOutputStream out;
Writer(PipedOutputStream out){
this.out = out;
}
@Override
public void run() {
try {
System.out.println("开始写入数据,等待6秒后。");
Thread.sleep(6000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
out.write("piped come here:".getBytes());
out.close();
}catch (IOException e) {
throw new RuntimeException("管道输出流失败");
}
}
}
public class PipedStreamDemo01 {
public static void main(String[] args) throws IOException {
PipedInputStream pips = new PipedInputStream();
PipedOutputStream pops = new PipedOutputStream();
pips.connect(pops);
Read r = new Read(pips);
Writer w = new Writer(pops);
new Thread(r).start();
new Thread(w).start();
}
}
|
|