class Read implements Runnable {
private PipedInputStream in;
Read(PipedInputStream in) {
this.in = in;
}
public void run() {
try {
byte[] buf = new byte[1024];
System.out.println("读取数据前,还没有阻塞");//
int len = in.read(buf);//阻塞式方法,当执行到这里时,假如发现PipedInputStream中没有数据可读,那么阻塞、等待。
//这时就会唤醒另外一个线程w, 并执行write()方法,往PipedInputStream中写入数据。
System.out.println("读取数据完成");//
String s = new String(buf,0,len);
System.out.println(s);
in.close();
}
catch (IOException e) {
throw new RuntimeException("读取失败");
}
}
}
class Write implements Runnable {
private PipedOutputStream out;
Write(PipedOutputStream out) {
this.out=out;
}
public void run() {
try {
System.out.println("准备写入数据,休眠5秒");//
Thread.sleep(5000);
out.write("piped lai la".getBytes());//写入数据
out.close();
}
catch (Exception e) {
throw new RuntimeException("输出败");
}
}
}
class PipedStreamDemo {
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();
}
}
在关键处加上了打印语句,希望可以帮助理解。作者: Hello_world_ 时间: 2013-7-29 07:50
read()当没有读到数据时,便会阻塞、等待, 操作系统里面有详细的介绍可以看看,read方法是一个阻塞式的方法!