Java中管道流

/*
集合中与IO结合的是Properties
IO中与多线程结合的是管道流(PipedInputStream、PipedOutputStream)
*/
import java.io.*;
class Read implements Runnable
{
	private PipedInputStream in;
	Read(PipedInputStream in)
	{
		this.in = in;
	}

	public void run()
	{
		try
		{
			byte [] buf =new byte[1024];
			int len = in.read(buf);
			String s = new String(buf,0,len);
			System.out.println(s);
			in.close();
		}
		catch (IOException ex)
		{
			throw new RuntimeException("管道读取流失败");
		}
	}
}

class Write implements Runnable
{
	private PipedOutputStream out;
	Write(PipedOutputStream out)
	{
		this.out = out;
	}

	public void run()
	{
		try
		{
			out.write("piped lai la".getBytes());
			out.close();
		}
		catch (IOException ex)
		{
			throw new RuntimeException("管道输出流失败");
		}
	}
}

class PipedStreamDemo
{
	public static void main(String[] args) throws IOException
	{
		PipedInputStream in = new PipedInputStream();
		PipedOutputStream out = new PipedOutputStream();
		in.connect(out);

		Read r = new Read(in);
		Write w = new Write(out);
		new Thread(r).start();
		new Thread(w).start();
	}
}

posted @ 2015-01-19 21:40  静以养身 俭以养德  阅读(397)  评论(0编辑  收藏  举报