The standard way of interrupting a command line program is by adding a Ctrl-C handler to your app:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// cleanup logic here
}
});
See this question for more details.
Since you insist. Here is an implementation when commands are executed in background threads. I hope the complexity of this example will deter you from 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;
do {
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 {
for (int i = 0; i < 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 :(");
// do cleanup
Thread.currentThread().interrupt();
}
}
};
}
}