Check the state of child process./thread in java

To run a child process/thread, you always need to check whether the process/thread is timeout or not.

Two ways to determine whether the process/thread is finished or not:

1)  Process p=new ....
   p.waitFor()     // a blocked waiting for the exit of the process

2)  Process p=new ..
   p.exitValue()   // actually, it is a function to check the return value of the process
                   // but we can use it to determine whether the process has been exit or not
                   // exitValue() will cause IllegalThreadStateException is the process has not been exit

   User the following exception handling method to check:

   while (true) {
       try {
           retVal = proc.exitValue();
           // process finished!
           break;
       } catch (IllegalThreadStateException e) {
           // process is still running...
               if (System.currentTimeMillis() >= endtime) {
                   // Process timed out
                   timedOut = true;
                   proc.destroy();
                   retVal = -1;
                   break;
               } else {
               try {
                   Thread.sleep(10000);
               } catch (InterruptedException e1) {
                   throw new RuntimeException(e1);
                                                                                                                                                                   }
           }
       }
   }

你可能感兴趣的:(java,state,multiple,Threads,processes)