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


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值