有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在关机挂钩中使用swing?

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

我意识到,如果我尝试创建一个新的JFrame,它会给我一个错误,因为它试图注册一个关闭钩子,但失败了,因为VM已经关闭了。我只是想知道是否真的有办法解决这个问题


共 (4) 个答案

  1. # 2 楼答案

    你真的不该这么做。从the ^{} 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. “关机挂钩也应该很快完成工作。”

      依赖任何可能需要一段时间才能完成工作的东西,或者无限期地阻止用户输入,比如JOptionPane对话框,都不是你应该在关闭钩子中做的事情

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

      Swing运行在AWT之上,AWT的底层事件调度线程也可能正在关闭。在关机时尝试使用Swing或AWT不仅会导致死锁,而且可能根本不起作用

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

      不能保证你的用户甚至可能收到你的消息,因为关机挂钩只保证在它正常退出或终止时运行--而不是在停止或中止时运行

  2. # 3 楼答案

    我不确定你的问题,但我认为当JVM关闭时,不可能运行或显示弹出窗口。就像你在准备睡觉的时候试着跑步?只是猜测而已。:)

  3. # 4 楼答案

    如果有的话,对你没有帮助

    关闭钩子是作为JVM关闭的一部分异步调用的,因此“确认”对话框不会真正确认任何内容,因为您无法停止或反转关闭过程。等待用户做出决定并不是关机挂钩的目的。交互式程序中的关机挂钩没有意义。 关机挂钩的真正用途是:

    for releasing resources and other housekeeping when the JVM shutsdown

    还需要注意的是,关闭钩子不会一直运行,更多信息请参见我的答案:How to shutdown java application correctly from C# one