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

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

问题描述

在这里作为答案提供的许多Swing片段中,有一个对 main 方法的28java.lang.Runnable%29> SwingUtilities#invokeLater

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通常可以构造并显示在主$ b $中b线程:以下典型代码是安全的,只要没有实现组件
(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组件和模型,事件调度线程中仅修改 。 - Java Concurrency在实践中 ,也讨论了这里此处。如果遵循此规则,则无法可靠地构造,修改或查询可能假定您 遵循该规则的任何组件或模型。程序可能出现以正常工作,但只能在不同的环境中神秘地失败。

"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.

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

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