我想要一個線程不斷接收來自kafka的消息,並且當我按下ctrl + C時我想關閉執行程序,但似乎addShutdownHook(...)方法不叫。如何強制呼叫addShutdownHook(...)
如何確保它會被調用?非常感謝!
public class wwwwwwww {
static ExecutorService executor = Executors.newFixedThreadPool(2);
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
Logger.getGlobal().info("***************destroying");
executor.shutdownNow();
}
});
}
public static void main(String[] args) throws Exception {
executor.submit(new Runnable() {
@Override
public void run() {
Logger.getGlobal().info("If you see this log message, then logging is configured correctly and you should see the shutdown hook message.");
while (true) {
Logger.getGlobal().info("Inside loop");
// ConsumerRecords<String, String> records = consumer.poll(100);
// for (ConsumerRecord<String, String> record : records) {
// System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value());
// }
}
}
});
}
}
[Java Shutdown hook not run]可能重複(http://stackoverflow.com/questions/12404712/java-shutdown-hook-not-run) – AxelH
此代碼完全按照假設在我的機器上執行;這真的只是一個獨立的Java應用程序嗎?你究竟如何執行代碼?你真的發送[SIGINT](https://en.wikipedia.org/wiki/Unix_signal#SIGINT)到JVM嗎?請提供[最小工作示例](https://stackoverflow.com/help/mcve)。 – errantlinguist
@ errantlinguist,感謝您的幫助,我點擊IDE中的停止按鈕,沒有任何銷燬信息輸出。 – Mike