简体   繁体   中英

How to exit an infinite while loop using user input?

This may sound like it's been asked before, but it's a bit different than the norm. I don't want the typical (After the user has run the program, I want it to ask "would you like to go again?"). I want to start a process (by typing a certain string which I've accomplished) and have it run for an infinite amount of time until the user stops it. There's no way of knowing how long it will run. This program happens to be a timer. So I need it to calculate how long it's been running, be able to be stopped at any given moment by the user, and print out how long it ran.

As of now, I'm not using any UI/GUI. Keeping it as simple as possible.

Set up a shutdown hook (code that runs when the JVM is halting):

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        // print stuff here
    }
}));

Get the user to type ctrl c at the command line to halt execution - your hook will run to print what you like as the JVM comes down.

Edit:

The above is brutal but simple, however if you didn't want to terminate the whole JVM, you're getting into the realm of "server events" to drive behaviour, which can take many forms to cause an action:

  • running your worker task in a separate thread and waiting for a command(s) at the terminal to halt (or other action) that thread - this is what I'd try first, and it would be very educational for you to do this
  • monitor a file system looking for the presence/absence of a file (lame, but it works with minimal code)
  • listening to ports for messages, an HTTP port of a web server is usually the weapon of choice, but we're starting to get a bit heavier on the server side
  • monitoring a JMS queue for messages - we're in Java EE space now with still more heaviness
  • any other "change in state" you care to implement

Edit 2:

This is a minimal implementation that works using a shutdown hook (start on the command line and press ctrl c to end and run the calculation code):

public static void main(String[] args) throws Exception {
    final long start = System.currentTimeMillis();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            double hours = (System.currentTimeMillis() - start) / 3600000d;
            System.out.println("Please enter the hourly rate");
            double hourlyRate = new Scanner(System.in).nextDouble();
            System.out.format("Program ran for %01.3f hours and cost $%02.2f", hours, hourlyRate * hours);
        }
    }));
    Thread.sleep(Long.MAX_VALUE); // Sleep "forever"
}

Could you start a Thread with daemon true, and then read a line in System.input, then interrupt the thread. java.util.Timer is possible too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM