Thread-launched running processes won't destroy (Java)

前端 未结 8 839
清歌不尽
清歌不尽 2021-02-01 08:41

Starting multiple threads and having each exec() then destroy() a running java process result in some of the process not being destroyed and still running after program exit. He

8条回答
  •  Happy的楠姐
    2021-02-01 09:21

    This is simply because before the threads execute the destroy call, your main program terminates and all the associated threads leaving the started processes running. To verify this, simply add a System.out call after the destroy and you will find it is not executed. To overcome this add a Thread.sleep at the end of your main method and you will not have the orphaned processes. The below does not leave any process running.

    public class ProcessTest {
    
    public static final void main (String[] args) throws Exception {
    
        for(int i = 0; i < 100; i++) {
            new Thread(new Runnable()
                {
                    public void run() {
                        try {
                            Process p = Runtime.getRuntime().exec(new String[]{"java", "InfiniteLoop"});
                            Thread.sleep(1);
                            p.destroy();
                            System.out.println("Destroyed");
                        }catch(IOException e) {
                            System.err.println("exception: " + e.getMessage());
                        } catch(InterruptedException e){
                            System.err.println("exception: " + e.getMessage());
                        }
                    }
                }).start();
        }
    
    
        Thread.sleep(1000);
    
    }
    

    }

提交回复
热议问题