多线程Java事件队列。为什么一切都应该在invokelater方法中?
在我正在阅读的书中,每个带有多线程的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);
}
});
}
(我指的是事件队列)。但是代码不是在主(EDT)线程中自动执行的吗
# 1 楼答案
桌面GUI应用程序通常以这种方式工作。gui有一个线程,应用程序的其余部分有一个或多个线程。使用
EventQueue
可以指定GUI线程应该从其他线程执行的操作# 2 楼答案
主线程与EDT不同。如果您添加
System.out.println(Thread.currentThread().getName()
,您将看到它在main()
内打印main
,在Runnable
的run()
方法内打印AWT-EventQueue-0
以下是a discussion of the history of the single threaded rule in Swing可能有助于让事情变得更清楚