The JVM can shutdown in either an orderly or abrupt manner. A shutdown hook runs for an orderly shutdown: when the last normal
thread terminates, someone calls System.exit
or by other platform specific means (such as typing Ctrl-C).
Shutdown hooks will not run for an abrupt shutdown of the JVM. As you are pressing the [x] in Netbeans lower right corner, this will cause an abrupt shutdown of the JVM and this is why the shutdown hook was not started.
For example :
public class ShutdownHook {
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("exit");
}
});
}
public static void main(String[] args) {
ShutdownHook sample = new ShutdownHook();
sample.attachShutDownHook();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you run the above code, and let the program complete normally, you will see exit
printed on the console. But if you press [x] (within 3 secs) to close it abruptly, the shutdown hook will not run and there will not be any exit
printed on the console.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…