【Java-IO】PipedInputStream和PipedOutputStream

在概念上,Java的管道不同于Unix/Linux系统中的管道。
在Unix/Linux中,运行在不同地址空间的两个进程可以通过管道通信。
在Java中,通信的双方应该是运行在同一进程中的不同线程。


可以通过Java IO中的PipedOutputStream和PipedInputStream创建管道。一个PipedInputStream流应该和一个PipedOutputStream流相关联。

一个线程通过PipedOutputStream写入的数据可以被另一个线程通过相关联的PipedInputStream读取出来。

public class TestPipe {

	public static void main(String args[]) throws IOException{
		PipedInputStream pis = new PipedInputStream();
		PipedOutputStream pos = new PipedOutputStream();
		//连接
		pis.connect(pos);
		//或者pos.connect(pis);
		//PipedOutputStream pos = new PipedOutputStream(pis);
		
		new Thread(new WriteThread(pos)).start();
		new Thread(new ReadThread(pis)).start();
		
	}
}

class WriteThread implements Runnable{
	PipedOutputStream pos;
	
	public WriteThread(PipedOutputStream pos) {
		this.pos=pos;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(2000);
			pos.write("write data".getBytes());
			pos.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
			
	}
	
}

class ReadThread implements Runnable{
	PipedInputStream pis;
	public ReadThread(PipedInputStream pis) {
		this.pis=pis;
	}

	@Override
	public void run() {
		byte[] buf = new byte[1024];
		try {
			int len = pis.read(buf); //read会阻塞,等待pipe的数据
			String s = new String(buf, 0, len);
			System.out.println(s);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值