JAVA IO进程间通信

PipedInputStream是从与其它线程共用的管道中读取数据,PipedOutputStream是向与其它线程共用的管道中写入数据。

例如:进程间通信

package com.awspaas.user.apps.yxt.oa.oajfw;

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

public class test {
	public static void main(String[] args) {
		send send = new send();
		recive recive = new recive();
		try {
			send.getOut().connect(recive.getIn());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread(send).start();
		new Thread(recive).start();
	}
}

/**
 * 发送消息
 * 
 * @author Administrator
 *
 */
class send implements Runnable {

	private PipedOutputStream out = null;

	public send() {
		out = new PipedOutputStream();
	}

	public PipedOutputStream getOut() {
		return this.out;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		String messages = "hello world";
		try {
			out.write(messages.getBytes());
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

/**
 * 接受消息
 * 
 * @author Administrator
 *
 */
class recive implements Runnable {

	private PipedInputStream in = null;

	public recive() {
		in = new PipedInputStream();
	}

	public PipedInputStream getIn() {
		return this.in;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		byte[] by = new byte[1024];

		try {
			in.read(by);
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("读出消息:" + new String(by));
	}

}



猜你喜欢

转载自blog.csdn.net/chaoyue1861/article/details/80078402