Java Process destroy() 方法



描述

Java Process destroy() 方法用于终止子进程。此 Process 对象表示的子进程将被强制终止。

声明

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

public abstract void destroy()

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

返回值

此方法不返回值。

异常

销毁记事本进程示例

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

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); // wait 10 seconds System.out.println("Waiting..."); Thread.sleep(10000); // kill the process p.destroy(); System.out.println("Process destroyed."); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

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

Creating Process...
Waiting...
Process destroyed.

销毁计算器进程示例

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

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); // wait 10 seconds System.out.println("Waiting..."); Thread.sleep(10000); // kill the process p.destroy(); System.out.println("Process destroyed."); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

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

Creating Process...
Waiting...
Process destroyed.

销毁 Windows 资源管理器进程示例

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

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); // wait 10 seconds System.out.println("Waiting..."); Thread.sleep(10000); // kill the process p.destroy(); System.out.println("Process destroyed."); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

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

Creating Process...
Waiting...
Process destroyed.
java_lang_process.htm
广告