(IO)管道流的应用---使用多线程技术

管道流---输入流与输出流结合

A线程负责往管道中写数据

B线程负责从管道中读数据

 

package com.gc.stream;

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

/**
 * 管道流
 *	将输入流与输出流进行结合
 *	A线程负责写,B线程负责读
 *	必须用多线程,一个线程用来写,另一个线程用来读
 * 
 * @author Administrator
 *
 */
public class PipedStreamDemo {
	
	public static void main(String[] args) throws IOException {
		//创建输出管道流---将数据写入到管道中
		PipedOutputStream pipeOut = new PipedOutputStream();
		//创建输入管道流---从管道中读数据
		PipedInputStream pipeIn = new PipedInputStream();
		//使用管道将输出流与输入流进行连接
		pipeIn.connect(pipeOut);
		
		//负责写的线程
		new Thread(new Outter(pipeOut)).start();
		
		//负责读的线程
		new Thread(new Inner(pipeIn)).start();
	}
}

/**
 * 负责读取数据,往管道中写的线程
 *
 */
class Outter implements Runnable {
	
	private PipedOutputStream out;
	
	public Outter(PipedOutputStream out) {
		this.out = out;
	}
	@Override
	public void run() {
		String data = "有点郁闷";
		try {
			out.write(data.getBytes());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

/**
 * 负责从管道中读取数据数据的线程
 *
 */
class Inner implements Runnable {
	private PipedInputStream in;
	
	public Inner(PipedInputStream in) {
		this.in = in;
	}
	@Override
	public void run() {
		byte[] buf = new byte[1024];
		try {
			int len = in.read(buf);
			String data = new String(buf,0,len);
			System.out.println("从管道流中读取到数据:"+data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值