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 ctrlc 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 ctrlc 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"
}
KeyListener)?