我有一个控制台应用程序,其中包含以下线程代码。当我按下Ctrl+C终止时,它似乎无法检测到控制键,我必须关闭命令提示窗口。
有什么线索可以说明为什么它无法检测到ctrl+c?
final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
for (int i = 0; i < threadPoolSize; i++) {
executor.submit(new MessageWorker(topicSubscriber));
}
//--
//Add JVM shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
/**
* @see java.lang.Thread#run()
*/
@Override
public void run() {
executor.shutdown();
try {
if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
log.warn("Executor did not terminate in the specified time.");
List<Runnable> droppedTasks = executor.shutdownNow();
log.warn("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed.");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});