加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java主线程与UI线程

发布时间:2020-12-15 00:26:08 所属栏目:Java 来源:网络整理
导读:在这里作为答案给出的许多Swing片段中,主要方法是调用 SwingUtilities#invokeLater : public class MyOneClassUiApp { private constructUi() { // Some Ui related Code } public static void main(String[] args) { SwingUtilities.invokeLater(new Runna
在这里作为答案给出的许多Swing片段中,主要方法是调用 SwingUtilities#invokeLater
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主要构建UI,或者这只是一个习惯,记得在其他情况下做吗?

解决方法

“Swing单线程规则:Swing组件和型号只能从事件调度线程创建,修改和查询.” – Java Concurrency in Practice,还讨论了 here和 here.如果不遵守此规则,那么您可以不可靠地构造,修改或查询任何可能假设您遵循规则的组件或模型.程序似乎可以正常工作,只能在不同的环境中神秘地失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读