为什么在 main 方法中使用 SwingUtilities.invokeLater? [英] Why to use SwingUtilities.invokeLater in main method?

查看:38
本文介绍了为什么在 main 方法中使用 SwingUtilities.invokeLater?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过多年的 Java 编程,我总是习惯于像这样创建我的 main() 方法:

After years of Java programming I always used to create my main() methods like this :

public static void main(String[] args) 
{
    runProgram();
}

但最近我从网上研究了一些代码,有时看到这个而不是上面通常使用的 main() :

But recently I studied some codes from the Web and saw this sometimes instead of the usual main() use above :

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

我只是想知道:

  • 为什么要使用这种方式而不是通常的 main() 方式?当我尝试时,我看不出有什么不同.
  • 这两种方式有什么区别?
  • Why to use this instead of the usual main() way ? I can't see any difference when I give it a try.
  • What is the difference between these two ways ?

感谢您阅读我和您的回答.

Thanks for reading me and your answers.

推荐答案

文档解释了原因.来自 初始线程

The docs explain why. From Initial Threads

为什么初始线程不简单地创建 GUI 本身?因为几乎所有创建或与 Swing 组件交互的代码都必须在事件调度线程上运行.

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.

来自事件调度线程

某些 Swing 组件方法在 API 规范中被标记为线程安全";这些可以从任何线程安全地调用.所有其他 Swing 组件方法都必须从事件调度线程中调用.忽略此规则的程序在大多数情况下可能会正常运行,但会出现难以重现的不可预测的错误.

Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

这篇关于为什么在 main 方法中使用 SwingUtilities.invokeLater?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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