【发布时间】:2020-11-19 09:21:53
【问题描述】:
我希望一个线程连续接收来自kafka的消息,并且我想在按ctrl+C时关闭执行程序,但似乎没有调用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 应用程序吗?你究竟是如何执行代码的?你真的向 JVM 发送了SIGINT 吗?请提供minimal working example。
-
@errantlinguist,感谢您的帮助,我在IDE中点击了停止按钮,没有任何破坏信息输出。
标签: java