Why to use SwingUtilities.invokeLater in main meth

2019-01-01 16:18发布

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

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

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

I simply want to know :

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

3条回答
怪性笑人.
2楼-- · 2019-01-01 16:20

The docs explain why. From Initial Threads

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.

and from The Event Dispatch Thread

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.

查看更多
时光乱了年华
3楼-- · 2019-01-01 16:34

Because the thread "main" started by VM is not the event dispatch thread.

查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 16:36

A few Swing components from the API are not thread safe,which means that they may cause some problems like deadlock,So its better to create and update such swing components by using Event dispatcher thread provided by Swing but not from the main thread or any other thread created from main.

查看更多
登录 后发表回答