1. 程式人生 > >java:管道流(線程間管道流)

java:管道流(線程間管道流)

sta pipe puts ble star ava ktr brush pri

class Send implements Runnable{

	PipedOutputStream pos = null;
	
	public Send()
	{
		this.pos = new PipedOutputStream();
	}
	
	public PipedOutputStream getPipedOutputStream()
	{
		return this.pos;
	}
	
	@Override
	public void run() {
		// TODO 自動生成的方法存根
		String str = "hello world!!!";
		try {
			this.pos.write(str.getBytes());
		} catch (IOException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		try {
			this.pos.close();
		} catch (IOException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
	}
	
}

class Receive implements Runnable{
	
	PipedInputStream pis = null;

	public Receive(){
		this.pis = new PipedInputStream();
	}
	
	public PipedInputStream getPipedInputStream()
	{
		return this.pis;
	}
	
	@Override
	public void run() {
		// TODO 自動生成的方法存根
		byte b[] = new byte[1024];
		int len = 0;
		try {
			len = this.pis.read(b);
		} catch (IOException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		try {
			this.pis.close();
		} catch (IOException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		System.out.println(new String(b,0,len) );
	}
	
}

public class PipedOutputStreamDemo {

	public static void main(String[] args) throws Exception {
		// TODO 自動生成的方法存根
		Send send =  new Send();
		Receive rec = new Receive();
		send.getPipedOutputStream().connect(rec.getPipedInputStream());
		new Thread(send).start();
		new Thread(rec).start();
	}

}

  

java:管道流(線程間管道流)