Java Process destroy() 方法



描述

Java Process destroy() 方法用於終止子程序。此 Process 物件表示的子程序將被強制終止。

宣告

以下是 java.lang.Process.destroy() 方法的宣告

public abstract void destroy()

引數

返回值

此方法不返回值。

異常

銷燬記事本程序示例

以下示例演示了 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
廣告

© . All rights reserved.