Java管道流

/*
 * 管道流,
 * 管道流也分为字节流(PipedOutputStream,PipedInputStream)和字符流(PipedReader,PipedWriter)
 * 本例采用字节流
 */
package Test2;

import java.io.*;

public class Demo_23_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Demo_23_6 d = new Demo_23_6();
	}

	public Demo_23_6()
	{
		//创建线程对象Sender
		Sender sender = new Sender();
		//创建线程对象Receiver
		Receiver receiver = new Receiver();
		
		PipedOutputStream out = sender.get();
		
		PipedInputStream in = receiver.get();
		
		try {
			//将输出发送到输入
			//将两个管道连接起来
			out.connect(in);
			
			//启动线程
			new Thread(sender).start();
			new Thread(receiver).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

class Sender implements Runnable
{

	private PipedOutputStream out = new PipedOutputStream();
	
	public PipedOutputStream get()
	{
		return out;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		String str = new String("Receiver 您好");
		
		try {
			//注意把字符流转化为字节流
			//写入要发送到的信息
			out.write(str.getBytes());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

class Receiver implements Runnable
{
	private PipedInputStream in = new PipedInputStream();

	public PipedInputStream get()
	{
		return in;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
	
		String s = null;
		
		/*
		 * 注意这里的1024,类PipedInputStream运用的是一个1024字节固定大小的循环缓冲区,
		 * 特别注意上面一句话,大小固定
		 * 如果当前缓冲区已经被占满,再试图写入的时候,该线程就会被阻塞,直到出现读取PipedInputStream的操作从缓冲区中删除数据
		 */
		byte[] a = new byte[1024];
		
		try {
			//读出数据
			int len = in.read(a);
			
			s = new String(a,0,len);
			
			System.out.println("收到了以下信息  : " + s);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值