gpt4 book ai didi

java - Windows 关机时不同的关机 Hook 行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:13 27 4
gpt4 key购买 nike

在我使用 Java 7 运行的 Eclipse E4 RCP 应用程序中,我遇到了一个问题,即当 Windows (7) 关闭或注销时,关闭 Hook 没有被执行。

经过一些研究,我发现了以下 Open JDK bug entry ,它创建一个空的 Swing JFrame 并使用关闭 Hook 。关闭 Hook 创建一个文件并写入它。虽然这个 bug 与我的问题没有直接关系,但我还是拿到了代码并对其进行了一些修改(见下文)。 (最大的修改是它不在钩子(Hook)里 hibernate 。)

之后我从该代码创建了一个 jar 并使用 javaw -jar jarname.jar 执行它。然后我尝试注销并关闭,在这两种情况下都写入了预期的文件。

之后,我修改了代码,使其创建一个空的 SWT Shell 并使用相同的关闭 Hook (另见下文)。注销并关闭预期文件时未写入。

现在我想知道为什么行为如此不同?我发现很难找到有关 Windows 和关机 Hook 的当前信息。

此外,如何确保关闭 Hook 在我的 RCP 应用程序中执行?

Swing 代码

public class ShutdownHookSwingBug {

public static final String fileName = "C:/shutdownhookbug_swing.log";

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

File myFile = new File(fileName);
myFile.delete();

Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
// Write "Hello " to a file
File myFile = new File(fileName);
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write("Hello ".getBytes());
outputStream.flush();
// Write "world!" and close the file
outputStream.write("world!".getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// Shouldn't happen.
}
}
});
}
}

SWT代码

public class ShutdownHookSwtBug {

public static final String fileName = "C:/shutdownhookbug_swt.log";

public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(300, 300);

File myFile = new File(fileName);
myFile.delete();

Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
File myFile = new File(fileName);
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write("Hello ".getBytes());
outputStream.flush();
outputStream.write("world!".getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// Shouldn't happen.
}
}
});

shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
}

最佳答案

作为解决方法,我在我的 E4 RCP 应用程序中使用了以下代码:

  SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(false);
}
});

但我对此并不满意,因为:

  • 我不知道它为什么有效
  • 我正在将 Swing 混合到一个纯 SWT 应用程序中

关于java - Windows 关机时不同的关机 Hook 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994180/

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