當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Process isAlive()用法及代碼示例


isAlive() 方法用於測試當前正在執行的進程是否存活。

用法

Public Boolean isAlive()

參數

NA

返回

isAlive() 方法返回兩個值:true 或 false

  1. 如果 process 對象執行的進程尚未終止,則該方法返回 true。
  2. 如果 process 對象執行的進程尚未終止,則該方法返回 false。

例子1

public class Process_isAliveMethodExample1 {
        public static void main(String[] args) {   
  try{
           //A process is created. 
          System.out.println("A process is created:");
         Process p = Runtime.getRuntime().exec("mspaint.exe");
      //Waits for the process until you terminate.
        p.waitFor();
      //Tests whether the current process is alive or not.
       System.out.println(p.isAlive());
      //The process is closed manually.
     System.out.println("Manually closes the notepad.");
       //Finally the wait is over.
      System.out.println("Wait is completed.");
    }catch(Exception e)
     {
       System.out.println(e);
     }
  }}

輸出:

A process is created:
false
Manually closes the notepad.
Wait is completed.

例子2

public class Process_isAliveMethodExample2 {
         public static void main(String[] args) {
    try{
          // At first Notepad is opened.
          System.out.println("Notepad will open");
          Process p1=Runtime.getRuntime().exec("notepad.exe");
        // Waits for the process p1 to terminate.
         p1.waitFor();
      //Tests whether the process p1 is alive.
        System.out.println(p1.isAlive());
     //After that notepad is opened.
         System.out.println("Ms paint will open");
         Process p2=Runtime.getRuntime().exec("mspaint.exe");
    //Again waits for the process to terminate. 
         p2.waitFor();
  // Tests whether the process p2 is alive.
        System.out.println(p2.isAlive());
      }catch(Exception e)
    {
        System.out.println("Ohho! an exception has occurred:");
    }
  }
}

輸出:

Notepad will open
false
Ms paint will open
False



相關用法


注:本文由純淨天空篩選整理自 Java Process isAlive() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。