gpt4 book ai didi

java - Java 中的主线程与 UI 线程

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:27 25 4
gpt4 key购买 nike

在此处作为答案给出的许多 Swing 片段中,有一个对 SwingUtilities#invokeLater 的调用来自 main 方法:

public class MyOneClassUiApp {

private constructUi() {
// Some Ui related Code
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyOneClassUiApp().constructUi();
}
});
}
}

但是根据Threads and Swing article ,从主线程构建 UI 是安全的:

A few methods are thread-safe: In the Swing API documentation, thread-safe methods are marked with this text:

This method is thread safe, although most Swing methods are not.

An application's GUI can often be constructed and shown in the main thread: The following typical code is safe, as long as no components (Swing or otherwise) have been realized:

public class MyApplication {
public static void main(String[] args) {
JFrame f = new JFrame("Labels");
// Add components to
// the frame here...
f.pack();
f.show();
// Don't do any more GUI work here...
}
}

那么,是否有真正的(线程安全)理由通过SwingUtilities#invokeLater在main中构建UI ,或者这只是一种习惯,记得在其他情况下这样做吗?

最佳答案

Swing 单线程规则:Swing 组件和模型应该从事件调度线程创建、修改和查询。”— Java Concurrency in Practice , 还讨论了 herehere .如果您遵守此规则,那么您将无法可靠地构建、修改或查询可能假设您确实遵守此规则的任何组件或模型。一个程序可能看起来工作正常,但在不同的环境中却神秘地失败了。由于违规行为可能不明显,请使用提到的方法之一验证正确使用 here .

关于java - Java 中的主线程与 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7156949/

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