原文鏈接:http://www.bdqn.cn/news/201303/8270.shtml 管道流可以實現兩個線程之間,二進位數據的傳輸。 管道流就像一條管道,一端輸入數據,別一端則輸出數據。通常要分別用兩個不同的線程來控制它們。 使用方法如下: [html] view plaincopy imp ...
原文鏈接:http://www.bdqn.cn/news/201303/8270.shtml
管道流可以實現兩個線程之間,二進位數據的傳輸。
管道流就像一條管道,一端輸入數據,別一端則輸出數據。通常要分別用兩個不同的線程來控制它們。
使用方法如下:
[html] view plaincopy-
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();
-
}
-
}
-
}
-
}
-