Java Process waitFor() 方法



描述

Java Process waitFor() 方法使当前线程等待(如有必要),直到此 Process 对象所代表的进程终止。如果子进程已终止,则此方法立即返回。如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。

声明

以下是java.lang.Process.waitFor() 方法的声明

public abstract int waitFor()

参数

返回值

此方法返回进程的退出值。按照惯例,0 表示正常终止。

异常

创建记事本进程以等待的示例

以下示例演示了 Process destroy() 方法的用法。我们为记事本可执行文件创建了一个 Process 对象。然后我们让进程等待并打印一条消息。

package com.tutorialspoint;

public class ProcessDemo {

   public static void main(String[] args) {
      try {
         // create a new process
         System.out.println("Creating Process...");
         String[] cmds = {"notepad.exe"};
         Process p = Runtime.getRuntime().exec(cmds);

         // cause this process to stop until process p is terminated
         p.waitFor();

         // when you manually close notepad.exe program will continue here
         System.out.println("Waiting over.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Creating Process...
Waiting over.

创建计算器进程以等待的示例

以下示例演示了 Process destroy() 方法的用法。我们为计算器可执行文件创建了一个 Process 对象。然后我们让进程等待并打印一条消息。

package com.tutorialspoint;

public class ProcessDemo {

   public static void main(String[] args) {
      try {
         // create a new process
         System.out.println("Creating Process...");
         String[] cmds = {"calc.exe"};
         Process p = Runtime.getRuntime().exec(cmds);

         // cause this process to stop until process p is terminated
         p.waitFor();

         // when you manually close calc.exe program will continue here
         System.out.println("Waiting over.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Creating Process...
Waiting over.

创建 Windows 资源管理器进程以等待的示例

以下示例演示了 Process destroy() 方法的用法。我们为 Windows 资源管理器可执行文件创建了一个 Process 对象。然后我们让进程等待并打印一条消息。

package com.tutorialspoint;

public class ProcessDemo {

   public static void main(String[] args) {
      try {
         // create a new process
         System.out.println("Creating Process...");
         String[] cmds = {"explorer.exe"};
         Process p = Runtime.getRuntime().exec(cmds);

         // cause this process to stop until process p is terminated
         p.waitFor();

         // when you manually close explorer.exe program will continue here
         System.out.println("Waiting over.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Creating Process...
Waiting over.
java_lang_process.htm
广告
© . All rights reserved.