java IO管道流

package com.io.file;

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


/**
 * @类功能说明:管道流
 * @类修改者:
 * @修改日期:
 * @修改说明:
 * @作者:matieli
 * @创建时间:May 26, 2012 9:56:29 AM
 * @版本:V1.0
 *
 */
class Read implements Runnable {
	private PipedInputStream in;

	public Read(PipedInputStream in) {
		this.in = in;
	}

	public void run() {
		try {
			
			byte[] b = new byte[1024];
			System.out.println("读取前,没有数据就阻塞");
			int len = in.read(b);
			System.out.println("读到数据,阻塞结束");
			String s = new String(b, 0, len);
			System.out.println(s);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

class Write implements Runnable {
	private PipedOutputStream out;

	public Write(PipedOutputStream out) {
		this.out = out;
	}

	public void run() {
		try {
			System.out.println("开始写入数据,等待5秒");
			Thread.sleep(5000);
			out.write("管道流来了".getBytes());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class PipedStreamDemo {
	public static void main(String[] args)throws Exception {
		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();
	}
}

猜你喜欢

转载自matieli.iteye.com/blog/1541690