读书人

java_IO源之PipedInputStream管道流的

发布时间: 2013-03-13 10:56:58 作者: rapoo

java_IO流之PipedInputStream管道流的使用

管道流可以实现两个线程之间,二进制数据的传输。

管道流就像一条管道,一端输入数据,别一端则输出数据。通常要分别用两个不同的线程来控制它们。

使用方法如下:

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();}}}}


读书人网 >编程

热点推荐