Process需要注意

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

    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("結束");
    
 }
 
}

 

發佈了109 篇原創文章 · 獲贊 0 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章