gpt4 book ai didi

java - ExecutorService 关闭钩子(Hook)

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:12 24 4
gpt4 key购买 nike

我有带有以下线程代码的控制台应用程序。似乎当我按 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();
}
}
});

最佳答案

只是阅读代码的猜测,但是,您的关机时间似乎设置为 10,000 秒,所以您不认为它正在退出我并不感到惊讶!

    final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
...
if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {

关于java - ExecutorService 关闭钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13966303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com