我有一个关于 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/