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

前端 未结 8 738
清歌不尽
清歌不尽 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条回答
  •  北海茫月
    2021-02-01 09:35

    I believe that according to link, a distinct process is spawned by the operating system in response to this call. This process has a lifetime independent of your Java program and threads within it so you would expect it to continue running after your program has exited. I just tried it on my machine and it appeared to work as expected:

    import java.io.*;
    
    class Mp {
    public static void main(String []args) {
        for(int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("1");
                        Process p = Runtime.getRuntime().exec
                            (new String[]{"notepad", ""});
                        System.out.println("2");
                        Thread.sleep(5);
                        System.out.println("3");
                        p.destroy();
                        System.out.println("4");
                    }
                    catch(IOException | InterruptedException e) {
                        e.printStackTrace();
                    }                    
                }
            }).start();
        }
    }
    }
    

提交回复
热议问题