英文:
java- not using event dispatching thread?
问题
首先,我知道关于这个主题有很多问题,但是没有一个问题回答了我想要了解的内容。
在查阅了一些问题时,我看到一个建议,即我们应该始终使用EDT来更新我们的GUI。
我的问题是,
- 我应该在什么时候使用它?请举一个例子。
- 如果我不使用它会发生什么?请举一个例子。不需要提供代码。
英文:
First of all, I know there are multiple questions out there on this topic, but none of them answers what I want to know.
During going through some questions, I came across a advice that we should always use EDT to update our GUI.
My questions are,
- When should I use it? One example please.
- What will happen if I don't use it? One example please. Code not required.
答案1
得分: 1
-
事件派发线程是处理所有与 Swing 相关的工作的线程。正如你所见,有时候你可以不明确地使用它来更新你的用户界面,尽管这被认为是不良做法。
-
事件派发线程负责你的 Swing 用户界面。它处理鼠标点击、事件、回调、窗口绘制等。每当一个
ActionListener
被调用时,它都是由事件派发线程调用的。 -
每当你向 Swing 注册一个监听器时,你都在使用事件派发线程,即使你没有明确提到它。
例如:
JButton button = new JButton(); button.addActionListener(e -> System.out.println("Clicked!"));
即使你没有提及事件派发线程,你仍然在使用它。当按钮被点击时,监听器是由事件派发线程调用的。
另一种使用事件派发线程的方式是使用
SwingUtilities.invokeLater()
。当你需要从非事件派发线程更新界面时,你会使用这个方法。Swing 不是线程安全的,这意味着不能从事件派发线程之外的线程更新界面是不安全的。即使在你的计算机上运行正常,也不能保证始终如此。你可以在这里阅读更多相关问题的信息。1 -
正如我所说,不使用事件派发线程是不安全的,因为 Swing 不对线程安全提供任何保证。
-
如果你使用 Swing,就总是在使用事件派发线程。但是你可以使用诸如
invokeLater()
和invokeAndWait()
的方法在事件派发线程上安排任务运行。
英文:
-
The Event Dispatching Thread is the thread where all Swing-related work should happen. As you've seen, you can sometimes get away with not explicitly using it to update your UI, although this is considered bad form.
-
The EDT is responsible for your Swing UI. It handles mouse clicks, events, callbacks, window drawing, etc. Every time an
ActionListener
is called, it's called by the EDT. -
Every time you register a listener with Swing, you're using the EDT, even if you don't explicitly mention it.
For example:
JButton button = new JButton(); button.addActionListener(e -> System.out.println("Clicked!"));
Even though you don't mention the EDT, you're still using it. The listener is called from the EDT when the button is clicked.
Another way to use the EDT is with
SwingUtilities.invokeLater()
. You would use this when you need to update the UI from a thread that's not the EDT. Swing is thread unsafe, which means that it's not safe to update the UI from outside the EDT. Even if things work on your computer, it's not guaranteed to always work. You can read a little more on a relevant question here. -
As I've said, not using the EDT is unsafe, since Swing makes no guarantees about thread safety.
-
If you use Swing, you're always using the EDT. But you can schedule tasks to run on the EDT with methods like
invokeLater()
andinvokeAndWait()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论