码迷,mamicode.com
首页 > 编程语言 > 详细

java 管道流PipedOutputStream和PipedInputStream基本操作

时间:2014-05-03 15:53:11      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:java   管道流   pipedinputstream   pipedoutputstream   

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基本操作

标签:java   管道流   pipedinputstream   pipedoutputstream   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!