Catching Control-C in Java
A short code snippet, demonstrating the use of Runtime.getRuntime().addShutdownHook().
RunWhenShuttingDown.run() below will run whenever the program is running and either Ctrl-C is pressed, loging off/shutingdown the computer, or clicking the X in the upper right hand corner.
slashdotRunWhenShuttingDown.run() below will run whenever the program is running and either Ctrl-C is pressed, loging off/shutingdown the computer, or clicking the X in the upper right hand corner.
public class CtrlC {
//~ Member variables --------------------------------------------------------------------------
private volatile boolean keepOn = true;
//~ Inner Classes -----------------------------------------------------------------------------
public class RunWhenShuttingDown extends Thread {
public void run() {
System.out.println("Control-C caught. Shutting down...");
keepOn = false;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//~ Methods -----------------------------------------------------------------------------------
public void runProgram() throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new RunWhenShuttingDown());
while(keepOn) {
System.out.println("running...");
Thread.sleep(1000);
}
System.out.println("Stopped running.");
}
public static void main(String[] args) throws InterruptedException {
new CtrlC().runProgram();
}
}
del.icio.us
technorati
[more]