gpt4 book ai didi

java - 停止所有 Awt/Swing 线程和监视器以及其他东西,以便只剩下主线程

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

我有以下内容

public static void main(String[] args) {
boolean running = true;
boolean foo= false;

while(running)
{
doSomeTask(); // might set foo true
if(foo) {
//This call waits/blocks until gui is done working.
fireUpSwingGui(); //does work...
foo=false;
godModeReleaseGUIandALLResourcesOnlyWantMainThreadLeft();
}
}
}

希望 godModeReleaseGUIandALLResourcesOnlyWantMainThreadLeft() 说明了一切。

请记住,当 foodoSomeTask() 中的某处再次变为 true 时,我们可能会在稍后阶段再次启动 gui。

最佳答案

看看AWT Threading Issues它解释了 AWT 应用程序退出的标准。您要关注的部分如下:

Therefore, a stand-alone AWT application that wishes to exit cleanly without calling System.exit must:

  • Make sure that all AWT or Swing components are made undisplayable when the application finishes. This can be done by calling Window.dispose on all top-level Windows. See Frame.getFrames.
  • Make sure that no method of AWT event listeners registered by the application with any AWT or Swing component can run into an infinite loop or hang indefinitely. For example, an AWT listener method triggered by some AWT event can post a new AWT event of the same type to the EventQueue. The argument is that methods of AWT event listeners are typically executed on helper threads.

用于演示的快速示例应用程序...

import java.awt.Frame;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class CloseAWT
{
private static boolean running = true;
private static int response = -1;

public static void main(String[] args)
{
boolean showSwing = true;
boolean checkFrames = true;
while (running)
{
if (showSwing)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
response = JOptionPane.showConfirmDialog(null, "Hello World?");
}
});
showSwing = false;
}
else
{
if (response >= 0 && checkFrames)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// topFrame.dispose();
Frame[] frames = Frame.getFrames();
System.out.printf("frames.length=%d\n", frames.length);
}
});
checkFrames = false;
}
}
}
}
}

为了确认行为符合预期,我在 JProfiler 中运行了它。单击"is"关闭确认对话框后,“AWT-EventQueue-0”线程被标记为死线程。在此之后唯一存活的线程是“主线程”和监听 Ctrl-Break 的线程。

我强烈推荐使用像 JProfiler 这样的东西, YourKit , JProbe或免费分析器之一,以确保您已正确释放所有组件并删除所有监听器。

最后一个想法...您可能想考虑将 GUI 作为一个单独的进程生成,并使用某种 IPC 在守护进程和 GUI 之间传递信息。虽然这会导致额外进程和 IPC 的额外开销,但它会给您更大的保证,即您的 GUI 在不再需要时已被完全清理。

关于java - 停止所有 Awt/Swing 线程和监视器以及其他东西,以便只剩下主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8430763/

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