not
在我的Java控制台应用程序中,我按了Ctrl + C并添加了一个使用Runtime.getRuntime()。addShutdownHook()执行正常关机的线程>
在此线程中,我在一些内部队列中处理所有艰巨的工作,并正常退出我的应用程序,这通常是我想要的。
但是,有时应用程序可能具有需要一些时间才能处理的内部队列(几分钟),如果是这样,我想选择第二次按Ctrl + C来强制退出应用程序。
我已经看到其他应用程序以这种方式工作,但是我找不到如何捕捉Java中的第二个Ctrl + C?
在我的Java控制台应用程序中,我按了Ctrl + C并添加了一个使用Runtime.getRuntime()。addShutdownHook()执行正常关闭的线程。在此线程中,我将处理所有...上的所有工作。] >> [[
not
import java.util.concurrent.atomic.AtomicBoolean;
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class Sigint {
private static void prepareShutdownHandling() {
// This would be the normal shutdown hook
final Thread shutdown = new Thread() {
@Override
public void run() {
// Simulate slow shutdown
for (int i = 0; i < 10; i++) {
System.out.println("Normal shutdown running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Normal shutdown finished");
System.exit(0);
}
};
Signal.handle(new Signal("INT"), new SignalHandler() {
private AtomicBoolean inShutdown = new AtomicBoolean();
public void handle(Signal sig) {
if (inShutdown.compareAndSet(false, true)) {
// Normal shutdown
shutdown.start();
} else {
System.err.println("Emergency shutdown");
System.exit(1);
}
}
});
}
public static void main(String args[]) {
prepareShutdownHandling();
while (true) {
System.out.println("Main program running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
not