gpt4 book ai didi

java - 如何在关闭 Hook 中使用 swing?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:04 25 4
gpt4 key购买 nike

是否有任何可能的方法将 swing 添加到关闭 Hook 中(即,在 VM 关闭时显示弹出窗口)?

我意识到,如果我尝试制作一个新的 JFrame,它会给我一个错误,因为它会尝试注册一个关闭 Hook ,但由于 VM 已经关闭而失败。我只是想知道实际上是否有任何解决方法

最佳答案

你真的不应该这样做。来自 the Runtime.addShutdownHook specification :

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

...

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. They should also not rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down. Attempts to use other thread-based services such as the AWT event-dispatch thread, for example, may lead to deadlocks.

Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.

...

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

此处的具体警告建议您不要这样做:

  1. “关闭 Hook 也应该快速完成它们的工作。”

    依赖任何可能需要一段时间才能完成的工作,或者无限期地阻止用户输入,比如JOptionPane 对话框,不是您应该在关闭 Hook 中做什么。

  2. “尝试使用其他基于线程的服务(例如 AWT 事件分发线程)可能会导致死锁”

    Swing 在 AWT 之上运行,AWT 的底层事件分发线程也可能处于关闭过程中。尝试在关机时使用 Swing 或 AWT 不仅会导致死锁,而且可能根本无法正常工作。

  3. “如果虚拟机中止,则无法保证是否会运行任何关闭 Hook ”

    无法保证您的用户甚至可能收到您的消息,因为关闭 Hook 只能保证在正常退出或终止时运行——不会在暂停或中止时运行。

关于java - 如何在关闭 Hook 中使用 swing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12120051/

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