gpt4 book ai didi

java - ShutdownHook何时被调用?

转载 作者:行者123 更新时间:2023-12-01 14:53:08 25 4
gpt4 key购买 nike

我有一个关于 Runtime.getRuntime().addShutdownHook() 的问题.

假设我在 main 中启动了两个线程。两个线程都在处理一个集合,List<String> commonColection .

当我按Ctrl+C时我想保存这个 Collection 。我的问题是:线程是否在调用 ShutdownHooks 之前停止,或者我是否需要显式终止我的线程,然后保存我的集合?

最佳答案

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

来自:Oracle Docu

当我读到这篇文章时,您将必须中止您的线程(不是Thread.abort!而是使用某种方法优雅地结束它们!)并保存您的集合。至少您必须确保保存集合的正确状态。

如果线程不是“无限”并且没有守护进程,您可以让它们完成。但我不建议这样做,因为关闭 Hook 应该很快返回。

关于java - ShutdownHook何时被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628672/

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