Send stop signal for command from user input in java programatically -


i executing simple command user gives options(args) , made logic args in java program in using wait() particular time command take minimum time execute.i saving data in file after that.

within time if user wants end process ,should able stop process smoothly giving input "exit" in command prompt.

please help.

the standard way of interrupting command line program adding ctrl-c handler app:

runtime.getruntime().addshutdownhook(new thread() {   public void run() {      // cleanup logic here   } }); 

see question more details.

since insist. here implementation when commands executed in background threads. hope complexity of example deter implementing it:

import java.util.scanner; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.timeunit;  public class shell {   private static final int num_parallel_commands = 5;   private static final int sleep_duration = 1000;    public static void main(string[] args) throws interruptedexception {     executorservice executor =          executors.newfixedthreadpool(num_parallel_commands);     try (scanner scanner = new scanner(system.in)) {       string command = null;            int counter = 0;       {         command = scanner.nextline();         switch (command) {           case "dostuff":             executor.submit(newdostuffcommand(++counter));             break;         }       } while (!command.equals("exit"));     }      executor.shutdownnow();     executor.awaittermination(1, timeunit.seconds);   }    private static runnable newdostuffcommand(final int counter) {     return new runnable() {       @override        public void run() {         try {           (int = 0; < 10; i++) {             system.out.println(counter + ": doing time consuming things...");             thread.sleep(sleep_duration);           }           system.out.println(counter + ": finished.");         } catch (interruptedexception e) {           system.out.println(counter + ": command interrupted :(");           // cleanup           thread.currentthread().interrupt();         }       }     };   } } 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -