首页 > 代码库 > java IO 管道流PipedOutputStream/PipedInputStream

java IO 管道流PipedOutputStream/PipedInputStream

详情:管道流的具体实现

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

//A线程发送数据给B线程
class AThread extends Thread{
	private PipedOutputStream out=new PipedOutputStream();
	
	public PipedOutputStream getOut() {
		return out;
	}
	public void run() {
			try {
				for (int i = 65; i <65+26; i++) {
				out.wait(i);
				}
				out.close();
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}
}
//B线程接收A线程发送的数据
class BThread extends Thread{
	private PipedInputStream in=null;
	
	public BThread(AThread aThread) throws Exception{
		in=new PipedInputStream(aThread.getOut());
	}
	public void run() {
		int len=-1;
		try {
			while((len=in.read())!=-1){
				System.out.println((char)len);
			}
			in.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}
public class PipedOutputStreamDemo {
	//管道流
	public static void main(String[] args) throws Exception {
		AThread a=new AThread();
		BThread b=new BThread(a);
		a.start();
		b.start();
	}
}

 

java IO 管道流PipedOutputStream/PipedInputStream