忽然有个疑惑,为什么这里的int len=in.read(buf);没有循环呢?是因为是字节数组而不是字符数组所以不用循环吗?
package io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
class Read implements Runnable{
private PipedInputStream in;
Read (PipedInputStream i){
this.in=i;
}
@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 (Exception e) {
// TODO: handle exception
throw new RuntimeException("管道输入流失败 ");
}
}
public static void main(String[]args) throws IOException{
PipedInputStream in=new PipedInputStream();
PipedOutputStream out=new PipedOutputStream();
in.connect(out);
Read r=new Read(in);
Write w=new Write(out);
new Thread(r).start();
new Thread(w).start();
}
}
class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out){
this.out=out;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("开始写入数据,等待6秒后");
Thread.sleep(6000);
out.write("piped lai le".getBytes());
out.close();
} catch (Exception e) {
throw new RuntimeException("管道输出流失败 ");
}
}
}
|
|