Process需要注意

来源:互联网 发布:希尔排序算法如何稳定 编辑:程序博客网 时间:2024/06/02 11:38

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    Process创建的子进程没有自己的终端或控制台

 import java.io.*;
import java.util.*;
public class PrivateClass
{
  
 static final String COMMAND = "java PrivateClass slave";
 public static void main(String[] args) throws Exception
 {
   
  
  if(args.length == 1 && args[0].equals("slave"))
  {
   for(int i = 20; i > 0; i--)
    {
    System.out.println( i +
    " bottles of beer on the wall" );
    System.out.println(i + " bottles of beer");
    System.out.println(
    "You take on down, pass it around,");
    System.out.println( (i-1) +
    " bottles of beer on the wall");
    System.out.println();
    }
  }
  else
  {
     //Process process =new ProcessBuilder("java PrivateClass", "slave").start();
     Process process = Runtime.getRuntime().exec(COMMAND);
     drainInBackground(process.getInputStream());//这样就可以看到调用程序运行的结果
     int exitValue = process.waitFor();
     System.out.println("exit value = " + exitValue);
  }
  
 }
 
 static void drainInBackground(final InputStream is)
 {
  new Thread()
  {
   public void run()
   {
    /*
     用下面这个是一样一样的
     Scanner s=new Scanner(is);
    while(s.hasNextLine())
     System.out.println(s.nextLine());
    System.out.println("结束");
    */

    try
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(is));
    String temp;
    while((temp=br.readLine())!=null)
     System.out.println(temp);
    }
    catch(IOException e)
    {
     
    }
   }
  }.start();
 }
}

经过实际测试,发现   System.out.println("exit value = " + exitValue);
这一句不是最后才打印出来的,它可能在子线程中间就输出
于是我改了一下子程序,算是小技巧吧

///////////////////////////////////////////////////////////////////////

import java.io.*;
import java.util.*;
public class PrivateClass
{
  
 static final String COMMAND = "java PrivateClass slave";
 public static void main(String[] args) throws Exception
 {
  if(args.length == 1 && args[0].equals("slave"))
  {
   for(int i = 80; i > 0; i--)
    {
    System.out.println( i +
    " bottles of beer on the wall" );
    System.out.println(i + " bottles of beer");
    System.out.println(
    "You take on down, pass it around,");
    System.out.println( (i-1) +
    " bottles of beer on the wall");
    System.out.println();
    }
  }
  else
  {
     Process process = Runtime.getRuntime().exec(COMMAND);
     ThreadInBack tib=new ThreadInBack(process.getInputStream());
     tib.start();
     tib.join();
     int exitValue = process.waitFor();
     System.out.println("exit value = " + exitValue);
  }
  
 }
 
}

class ThreadInBack extends Thread
{
 InputStream is;
    public ThreadInBack(InputStream is)
 {
  this.is=is;
 }
 public void run()
 {
    
  Scanner s=new Scanner(is);
  while(s.hasNextLine())
   System.out.println(s.nextLine());
  System.out.println("结束");
    
 }
 
}