在我正在阅读的书中,每个使用多线程的 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);
}
});
}
(我的意思是 EventQueue)。但代码不是在主 (EDT) 线程中自动执行吗?
最佳答案
主线程与 EDT 不同。如果你添加 System.out.println(Thread.currentThread().getName()
你会看到它在 main()
中打印出 main
> 和 AWT-EventQueue-0
在 Runnable
的 run()
方法中。
这里是 a discussion of the history of the single threaded rule in Swing这可能有助于让事情变得更清楚。
关于Java 事件队列。为什么一切都应该在 invokelater 方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5780936/