-1

I have read a number of questions and answers about how to close a currently running thread, but many use the method "desroy()", which is deprecated.

I am working in Java and have written code that uses multithreading to simultaneously open the Notepad executable multiple times. I now want to close these executable files. Is there a way to close these files by closing/ending the currently running threads without invoking a deprecated method?

Please feel free to let me know if I need to elaborate upon, or clarify, any points. I really appreciate any help you can provide!

  • 1
    Since you created the process yourself, you can close it by calling [Process.destroy](https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#destroy\(\)). See also http://stackoverflow.com/questions/6356340/killing-a-process-using-java – dnault Jun 21 '16 at 21:06

3 Answers3

0

If you start a Process in a Thread and that process finishes or is destroy()ed then the thread can complete naturally. Alternatively you could interrupt the thread without waiting for the process to complete, though this is not idea as you lose control of that process.

Note: even when Thread.destroy() was available it didn't kill a Process started in that thread.

In short, try stopping the Process run from the thread.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Synchronously signal it to stop (using whatever mechanism you want), join on it, then let it get garbage collected.

Andy
  • 1,663
  • 10
  • 17
0

I suppose using deprecated method can be quite dangerous, and there is nice article about this here : https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html You could use Thread.interrupt and implement a catch like this in your run() method:

  catch (InterruptedException ex){  
 Thread.currentThread().interrupt(); 
    }

Override interrupt method in order to close your stream:

    private InputStream in;
    @Override
        public void interrupt() {
            super.interrupt();
            try {
                in.close(); 
            } catch (IOException e) {}
        }

and then in your method main() do something like this:

       Thread t = new MyThread(in);
        t.start();
        Thread.sleep(1000);
        t.interrupt();
        t.join(); 

Hope this will give you some ideas in which direction to continue..

anna_arshi
  • 38
  • 8