读书人

管道源

发布时间: 2012-10-29 10:03:53 作者: rapoo

管道流

管道流的作用是可以进行两个线程间的通信,它分为管道输出流(PipedOutputStream)和管道输入(PipedInputStream).如果要进行管道输出,则必须把输出流连到输入流上,在PipedOutputStream类上有如下的方法用于连接管道.

public void connect(PipedInputStream snk) throws IOException

?

管道流的验证

?

package com.zss;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class Send implements Runnable {

?private PipedOutputStream pos = null;

?public Send() {

??this.pos = new PipedOutputStream();
?}

?public void run() {
??String str = "Hello world";
??try {
???this.pos.write(str.getBytes());
??} catch (IOException e) {
???e.printStackTrace();
??} finally {

???try {
????this.pos.close();
???} catch (IOException e) {
????e.printStackTrace();
???}
??}

?}

?public PipedOutputStream getPos() {
??return this.pos;
?}

}

class Receive implements Runnable {

?private PipedInputStream pis = null;

?public Receive() {
??this.pis = new PipedInputStream();

?}

?public void run() {
??byte bt[] = new byte[1024];

??int len = 0;
??try {
???len = this.pis.read(bt);
??} catch (IOException e) {
???e.printStackTrace();
??}finally{
???try {
????this.pis.close();
???} catch (IOException e) {
????e.printStackTrace();
???}
??}
??
??System.out.println("接收的内容为:"+new String(bt,0,len));

?}
?
?public PipedInputStream getPis(){
??return this.pis;
?}

}

public class PipedStreamDemo{
?
?public static void main(String args[]){
??Send send=new Send();
??Receive receive=new Receive();
??
??try {
???send.getPos().connect(receive.getPis());
??} catch (IOException e) {
???e.printStackTrace();
??}
??
??new Thread(send).start();
??new Thread(receive).start();
?}
?
}

?

读书人网 >编程

热点推荐