- 管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信。
创建子进程Java有两种方式//第一种
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("java -jar app2.jar");
//第二种
ProcessBuilder pb = new ProcessBuilder("java", "-jar","app2.jar");
Process p = pb.start();第二种方式操作更方便,实例如下。
父进程App.classtry{
ProcessBuilder pb=new ProcessBuilder("java -jar app2.jar".split(" "));
pb.directory(new File("e:/temp/clean_day/jar/"));
//标准错误和输入流合并为输入流
pb.redirectErrorStream(true);
//创建子进程
Process p=pb.start(); //使用Process的输入流接收子进程发送的消息
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
//使用Process的输出流向子进程发送消息,并把PrintWriter设置为自动flush.
PrintWriter wr=new PrintWriter(new OutputStreamWriter(p.getOutputStream()),true);
String lineStr;
while((lineStr=br.readLine())!=null){
System.out.println("收到子进程的消息:"+lineStr);
//向子进程发送消息
wr.println(System.currentTimeMillis());
}
wr.close();
br.close();
}catch(Exception ex){
System.out.println(ex.getMessage());
}子进程App2.class
try{
System.out.println("子进程启动成功");
System.out.println(System.currentTimeMillis()); //利用标准输入来接收父进程发送的消息
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lineStr;
while ((lineStr = br.readLine()) != null) {
System.out.println("child\t"+lineStr);
}
br.close();
}catch(Exception ex){
System.out.println(ex.getMessage());
} - (非进程,而是线程)PipedInputStream、PipedOutStream、PipedReader、PipedWriter管道流
public class App { public static void main(String[] args) {
PpWriter wr=new PpWriter();
PpReader rd=new PpReader(wr); Thread wrth=new Thread(wr);
wrth.start(); Thread rdth=new Thread(rd);
rdth.start();
}
} /**
* 管道写
* App.java:Temp
* 2015年3月26日
* @author kevin.zhai(韩旭)
*/
class PpWriter implements Runnable{
private PipedWriter pipedWriter; public PpWriter(){
this.pipedWriter=new PipedWriter();
} @Override
public void run() {
try {
while(true){
//因为读使用了readline,因此这里要换行
String sendStr=System.currentTimeMillis()+"\r\n";
this.pipedWriter.write(sendStr);
System.out.println("父发送:"+sendStr);
Thread.sleep(1000);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} public PipedWriter getPipedWriter() {
return pipedWriter;
}
} /**
* 管道读
* App.java:Temp
* 2015年3月26日
* @author kevin.zhai(韩旭)
*/
class PpReader implements Runnable{
private PipedReader pipedReader; public PpReader(PpWriter ppWriter){
try {
//读需要先和写建立连接,否则报异常:Pipe not connected
this.pipedReader=new PipedReader(ppWriter.getPipedWriter());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() { try(BufferedReader br=new BufferedReader(this.pipedReader)){
while(true){
System.out.println("子接收:"+br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}