首页 > 编程语言 > 详细

java 管道流PipedOutputStream和PipedInputStream基本操作

时间:2014-05-03 15:52:50      阅读:387      评论:0      收藏:0      [点我收藏+]

java的管道流要PipedOutputSream和PipedInputStream结合起来使用,管道流主要用来进行线程之间的通信。

上代码

import java.io.*;

public class PipeStreamDemo
{
	public static void main(String[] args)
	{
		PipedOutputStream out=null;
		PipedInputStream in=null;
		Sender sender=new Sender();
		Receiver receiver=new Receiver();
		out=sender.getOutputStream();
		in=receiver.getInputStream();
		try 
		{
			out.connect(in);
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sender.start();
		receiver.start();
	}
}

class Sender extends Thread
{
	private PipedOutputStream out=new PipedOutputStream();
	public PipedOutputStream getOutputStream()
	{
		return out;
	}
	public void run()
	{
		String str="Hello, my name is cjc!";
		try 
		{
			out.write(str.getBytes());
			out.close();
			System.out.println("The sender Thread sends string \""+str+"\".");
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
class Receiver extends Thread
{
	private PipedInputStream in=new PipedInputStream();
	public PipedInputStream getInputStream()
	{
		return in;
	}
	public void run()
	{
		byte[] b=new byte[1024];
		try 
		{
			int num=in.read(b);
			in.close();
			if(num==-1)
			{
				System.out.println("The receiver Thread receives nothing!!!");
			}
			else
			{
				System.out.println("The receiver Thread receices \""+new String(b,0,num)+"\".");
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
bubuko.com,布布扣

java 管道流PipedOutputStream和PipedInputStream基本操作,布布扣,bubuko.com

java 管道流PipedOutputStream和PipedInputStream基本操作

原文:http://blog.csdn.net/cjc211322/article/details/24887119

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!