原文链接:http://www.bdqn.cn/news/201303/8270.shtml
管道流可以实现两个线程之间,二进制数据的传输。
管道流就像一条管道,一端输入数据,别一端则输出数据。通常要分别用两个不同的线程来控制它们。
使用方法如下:
-
import java.io.IOException;
-
import java.io.PipedInputStream;
-
import java.io.PipedOutputStream;
-
public class PipedInputStreamTest {
-
public static void main(String[] args) {
-
//管道输出流
-
PipedOutputStream out = new PipedOutputStream();
-
//管道输入流
-
PipedInputStream in = null;
-
try {
-
//连接两个管道流。或者调用connect(Piped..);方法也可以
-
in = new PipedInputStream(out);
-
Thread read = new Thread(new Read(in));
-
Thread write = new Thread(new Write(out));
-
//启动线程
-
read.start();
-
write.start();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
class Write implements Runnable {
-
PipedOutputStream pos = null;
-
public Write(PipedOutputStream pos) {
-
this.pos = pos;
-
}
-
public void run() {
-
try {
-
System.out.println("程序将在3秒后写入数据,请稍等。。。");
-
Thread.sleep(3000);
-
pos.write("wangzhihong".getBytes());
-
pos.flush();
-
} catch (IOException e) {
-
e.printStackTrace();
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
} finally {
-
try {
-
if (pos != null) {
-
pos.close();
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
-
class Read implements Runnable {
-
PipedInputStream pis = null;
-
public Read(PipedInputStream pis) {
-
this.pis = pis;
-
}
-
public void run() {
-
byte[] buf = new byte[1024];
-
try {
-
pis.read(buf);
-
System.out.println(new String(buf));
-
} catch (IOException e) {
-
e.printStackTrace();
-
} finally {
-
try {
-
if (pis != null) {
-
pis.close();
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}