Java EventQueue。为什么一切都应该在invokelater方法中?

时间:2021-10-30 00:14:53

in the book that i'm reading, every example of GUI with multithreading has something like that:

在我正在阅读的书中,带有多线程的GUI的每个例子都有类似的东西:

public static void main(String[] args) throws Exception
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            JFrame frame = new SomeKindOfFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    });
}

(i mean EventQueue). but isn't the code automatically executed in the main (EDT) thread?

(我的意思是EventQueue)。但是不是主(EDT)线程中自动执行的代码?

2 个解决方案

#1


6  

Desktop GUI applications usually work in this way. There is one thread for gui and one or several threads for rest of application. Using EventQueue you specify what GUI thread should do from other threads.

桌面GUI应用程序通常以这种方式工作。 gui有一个线程,其余应用有一个或多个线程。使用EventQueue指定GUI线程应该从其他线程执行的操作。

#2


13  

The main thread isn't the same as the EDT. If you add System.out.println(Thread.currentThread().getName() you'll see it print out main within main() and AWT-EventQueue-0 when within the run() method of the Runnable.

主线程与EDT不同。如果你添加System.out.println(Thread.currentThread()。getName(),你会看到它在runnable的run()方法中打印出main()和AWT-EventQueue-0中的main。

Here is a discussion of the history of the single threaded rule in Swing that might help make things clearer.

下面讨论Swing中单线程规则的历史,这可能有助于使事情更加清晰。

#1


6  

Desktop GUI applications usually work in this way. There is one thread for gui and one or several threads for rest of application. Using EventQueue you specify what GUI thread should do from other threads.

桌面GUI应用程序通常以这种方式工作。 gui有一个线程,其余应用有一个或多个线程。使用EventQueue指定GUI线程应该从其他线程执行的操作。

#2


13  

The main thread isn't the same as the EDT. If you add System.out.println(Thread.currentThread().getName() you'll see it print out main within main() and AWT-EventQueue-0 when within the run() method of the Runnable.

主线程与EDT不同。如果你添加System.out.println(Thread.currentThread()。getName(),你会看到它在runnable的run()方法中打印出main()和AWT-EventQueue-0中的main。

Here is a discussion of the history of the single threaded rule in Swing that might help make things clearer.

下面讨论Swing中单线程规则的历史,这可能有助于使事情更加清晰。