Java 中的主线程与 UI 线程 [英] Main Thread vs. UI Thread in Java

查看:64
本文介绍了Java 中的主线程与 UI 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In many Swing snippets given here as answers, there is a call to SwingUtilities#invokeLater from the main method:

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();
            }
        });
    }
}

但根据 线程和 Swing 文章,可以安全地从主线程构建 UI:

But according to the Threads and Swing article, it is safe to construct UI from main thread:

一些方法是线程安全的:在 Swing API 文档中,线程安全方法用以下文字标记:

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

这个方法是线程安全的,尽管大多数 Swing 方法不是.

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

应用程序的 GUI 通常可以构建并显示在主界面中线程:以下典型代码是安全的,只要没有组件(Swing 或其他方式)已经实现:

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,或者这只是一种习惯,要记住在其他情况下这样做?

So, is there a real (thread safety) reason to construct the UI in main through SwingUtilities#invokeLater, or this is just a habit, to remember do it in other cases?

推荐答案

"Swing 单线程规则:只应创建、修改和查询 Swing 组件和模型em> 来自事件调度线程."—Java 并发实践,还讨论了这里此处.如果您遵循此规则,那么您将无法可靠地构建、修改或查询任何可能假定您确实遵循此规则的组件或模型.一个程序可能看起来正常工作,但在不同的环境中却神秘地失败了.由于违规行为可能不清楚,请使用此处中提到的方法之一验证正确使用.

"The Swing single-thread rule: Swing components and models should be created, modified, and queried only from the event-dispatching thread."—Java Concurrency in Practice, also discussed here and here. If you don't follow this rule, then you can't reliably construct, modify or query any component or model that may have assumed that you did follow the rule. A program may appear to work correctly, only to fail mysteriously in a different environment. As violations may be obscure, verify correct usage by using one of the approaches mentioned here.

这篇关于Java 中的主线程与 UI 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆